Compare commits

...

402 Commits

Author SHA1 Message Date
Frappe PR Bot
26f0687834 chore(release): Bumped to Version 15.121.3
## [15.121.3](https://github.com/frappe/erpnext/compare/v15.121.2...v15.121.3) (2026-09-15)

### Bug Fixes

* % Amount Billed exceeds 100% on fully rejected Purchase Receipts ([#58897](https://github.com/frappe/erpnext/issues/58897)) ([c31ae57](c31ae577e4))
* **accounts:** add permission checks on `execute_repost_payment_ledger` (backport [#58980](https://github.com/frappe/erpnext/issues/58980)) ([#58981](https://github.com/frappe/erpnext/issues/58981)) ([85a1529](85a152946e))
* **accounts:** add permission checks on `invoice_discounting.get_invoices` (backport [#58975](https://github.com/frappe/erpnext/issues/58975)) ([#58989](https://github.com/frappe/erpnext/issues/58989)) ([62b9f31](62b9f31297))
* **accounts:** reject disabled price lists in buying and selling ([#58891](https://github.com/frappe/erpnext/issues/58891)) ([47662b9](47662b9af2))
* **accounts:** stop counting received qty on non-stock invoice returns (backport [#58924](https://github.com/frappe/erpnext/issues/58924)) ([#58928](https://github.com/frappe/erpnext/issues/58928)) ([228108a](228108ad4c))
* Backfill `not_applicable` on Item Tax Template Details for German companies (backport [#54682](https://github.com/frappe/erpnext/issues/54682)) (backport [#54686](https://github.com/frappe/erpnext/issues/54686)) ([#58952](https://github.com/frappe/erpnext/issues/58952)) ([f943368](f9433683ec))
* keep a dunning claimable until its interest is paid too ([11c6f0d](11c6f0d02c))
* **manufacturing:** handle empty raw materials in workstation ([#58927](https://github.com/frappe/erpnext/issues/58927)) ([c72bc69](c72bc6925b))
* prevent disabled items from being used in bom ([#58997](https://github.com/frappe/erpnext/issues/58997)) ([7429a26](7429a260f6))
* reset price list fallback when changing parties ([#58893](https://github.com/frappe/erpnext/issues/58893)) ([f981791](f981791012))
* resolve conflicts ([e84a946](e84a94642d))
* resolve conflicts ([00729a8](00729a8d62))
* **selling:** add email permission check on `send_emails` (backport [#58935](https://github.com/frappe/erpnext/issues/58935)) ([#58937](https://github.com/frappe/erpnext/issues/58937)) ([e37ba3f](e37ba3f8cf))
* **selling:** exclude fully billed orders from the invoice picker (backport [#58966](https://github.com/frappe/erpnext/issues/58966)) ([#58968](https://github.com/frappe/erpnext/issues/58968)) ([52ea7ed](52ea7ed606))
* **stock:** distribute additional costs when incoming items have no value ([10987b1](10987b11cc))
* **stock:** do not rebuild the Warehouse tree on an account map miss (backport [#58956](https://github.com/frappe/erpnext/issues/58956)) ([#58972](https://github.com/frappe/erpnext/issues/58972)) ([f59a6ec](f59a6ec882))
* **stock:** guard inventory dimension lookup without reference document ([#58889](https://github.com/frappe/erpnext/issues/58889)) ([7ee54ba](7ee54ba08b))
* **stock:** preserve rates for unsaved mapped rows (backport [#58852](https://github.com/frappe/erpnext/issues/58852)) ([#58898](https://github.com/frappe/erpnext/issues/58898)) ([32d8c35](32d8c359ed))
* **stock:** recalculate billing status of returned delivery notes (backport [#58953](https://github.com/frappe/erpnext/issues/58953)) ([#58986](https://github.com/frappe/erpnext/issues/58986)) ([563615c](563615c77e))
* **stock:** remove empty delivery stops after mapping ([#58896](https://github.com/frappe/erpnext/issues/58896)) ([0099e7e](0099e7ec4f))
* **stock:** set item_name to fetch if empty in packing slip item ([#58925](https://github.com/frappe/erpnext/issues/58925)) ([99afc2e](99afc2e6eb))
* **stock:** set item_name to fetch if empty in packing slip item ([#58925](https://github.com/frappe/erpnext/issues/58925)) ([9ba2159](9ba2159720))
* **stock:** show actual outgoing rate in ledger preview ([#58700](https://github.com/frappe/erpnext/issues/58700)) ([372244e](372244e6b2))
* **subcontracting:** validate project across the subcontracting flow ([#58965](https://github.com/frappe/erpnext/issues/58965)) ([1150d8e](1150d8e9b0))
* user not able to set valuation rate zero in stock reco (backport [#58800](https://github.com/frappe/erpnext/issues/58800)) ([#58821](https://github.com/frappe/erpnext/issues/58821)) ([3bd194e](3bd194e986))
* validate shelf life for automatically created expiring batches ([#58911](https://github.com/frappe/erpnext/issues/58911)) ([00e02f0](00e02f07ac))
2026-09-15 18:35:09 +00:00
Diptanil Saha
f2cfe30596 Merge pull request #59072 from frappe/version-15-hotfix
chore: release v15
2026-09-16 00:03:25 +05:30
Sudharsanan Ashok
641f8e56a2 Merge pull request #59012 from frappe/mergify/bp/version-15-hotfix/pr-58997
fix: prevent disabled items from being used in BOM (backport #58997)
2026-09-15 22:07:10 +05:30
Sudharsanan Ashok
f6bac4c6ee Merge pull request #59077 from frappe/mergify/bp/version-15-hotfix/pr-58925
fix(stock): set item_name to fetch if empty in packing slip item (backport #58925)
2026-09-15 18:55:46 +05:30
mergify[bot]
112350dd65 fix(regional)!: remove irs_1099_print whitelisted method (backport #58976) (#58991)
Co-authored-by: Diptanil Saha <diptanil@frappe.io>
2026-09-15 18:40:22 +05:30
Afsal Syed
99afc2e6eb fix(stock): set item_name to fetch if empty in packing slip item (#58925)
(cherry picked from commit f130c64530)

# Conflicts:
#	erpnext/stock/doctype/packing_slip_item/packing_slip_item.json
2026-09-15 18:35:56 +05:30
Sudharsanan Ashok
1c576a6f1c Merge pull request #59075 from frappe/revert-58942-mergify/bp/version-15-hotfix/pr-58925
Revert "fix(stock): set item_name to fetch if empty in packing slip item (backport #58925)"
2026-09-15 18:05:44 +05:30
Sudharsanan Ashok
618864a051 Revert "fix(stock): set item_name to fetch if empty in packing slip item (backport #58925)" 2026-09-15 17:47:47 +05:30
Sudharsanan Ashok
d9ea9a5430 Merge pull request #58942 from frappe/mergify/bp/version-15-hotfix/pr-58925
fix(stock): set item_name to fetch if empty in packing slip item (backport #58925)
2026-09-15 17:42:52 +05:30
Afsal Syed
9ba2159720 fix(stock): set item_name to fetch if empty in packing slip item (#58925)
(cherry picked from commit f130c64530)

# Conflicts:
#	erpnext/stock/doctype/packing_slip_item/packing_slip_item.json
2026-09-15 16:38:36 +05:30
Sudharsanan Ashok
602803cce0 Merge pull request #59040 from frappe/mergify/bp/version-15-hotfix/pr-58965
fix(subcontracting): validate project across the subcontracting flow  (backport #58965)
2026-09-13 17:53:20 +05:30
Sudharsanan11
e84a94642d fix: resolve conflicts 2026-09-13 12:12:16 +05:30
Sudharsanan Ashok
1150d8e9b0 fix(subcontracting): validate project across the subcontracting flow (#58965)
(cherry picked from commit fe25746feb)

# Conflicts:
#	erpnext/subcontracting/doctype/subcontracting_order/subcontracting_order.py
#	erpnext/subcontracting/doctype/subcontracting_order/test_subcontracting_order.py
#	erpnext/subcontracting/doctype/subcontracting_receipt/mapper.py
2026-09-13 06:29:16 +00:00
pandiyan
7429a260f6 fix: prevent disabled items from being used in bom (#58997)
Co-authored-by: Ajish18 <ajishiyappan1@gmail.com>
(cherry picked from commit e6f431a8d6)
2026-09-12 21:58:25 +05:30
mergify[bot]
f9433683ec fix: Backfill not_applicable on Item Tax Template Details for German companies (backport #54682) (backport #54686) (#58952)
* fix: Backfill `not_applicable` on Item Tax Template Details for German companies (backport #54682) (#54686)

Co-authored-by: Raffael Meyer <14891507+barredterra@users.noreply.github.com>
fix: Backfill `not_applicable` on Item Tax Template Details for German companies (#54682)
(cherry picked from commit a22d773341)

# Conflicts:
#	erpnext/patches.txt

* chore: resolve conflict

* fix: compare zero-rate row count, not just the identifier set

* chore: correct comment on account name uniqueness

* test: cover German `not_applicable` backfill patch

Run the patch against a company seeded from the shipped German defaults:
matching defaults are backfilled, customised templates and templates with a
duplicate account name are left alone, and a rerun changes nothing.

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
Co-authored-by: barredterra <14891507+barredterra@users.noreply.github.com>
2026-09-11 13:21:39 +02:00
mergify[bot]
62b9f31297 fix(accounts): add permission checks on invoice_discounting.get_invoices (backport #58975) (#58989)
Co-authored-by: Diptanil Saha <diptanil@frappe.io>
2026-09-11 04:42:54 +00:00
mergify[bot]
85a152946e fix(accounts): add permission checks on execute_repost_payment_ledger (backport #58980) (#58981)
Co-authored-by: Diptanil Saha <diptanil@frappe.io>
2026-09-11 09:38:50 +05:30
mergify[bot]
563615c77e fix(stock): recalculate billing status of returned delivery notes (backport #58953) (#58986)
Co-authored-by: Raffael Meyer <14891507+barredterra@users.noreply.github.com>
2026-09-11 00:56:26 +02:00
Mihir Kandoi
52ea7ed606 fix(selling): exclude fully billed orders from the invoice picker (backport #58966) (#58968) 2026-09-10 20:51:03 +05:30
mergify[bot]
f59a6ec882 fix(stock): do not rebuild the Warehouse tree on an account map miss (backport #58956) (#58972)
Co-authored-by: Mihir Kandoi <kandoimihir@gmail.com>
2026-09-10 13:09:00 +00:00
Sudharsanan Ashok
bb0140ff3f Merge pull request #58946 from frappe/mergify/bp/version-15-hotfix/pr-58927
fix(manufacturing): handle empty raw materials in workstation (backport #58927)
2026-09-10 18:08:52 +05:30
pandiyan
c72bc6925b fix(manufacturing): handle empty raw materials in workstation (#58927)
(cherry picked from commit 3be0c7801a)
2026-09-10 11:44:42 +05:30
mergify[bot]
e37ba3f8cf fix(selling): add email permission check on send_emails (backport #58935) (#58937)
Co-authored-by: Diptanil Saha <diptanil@frappe.io>
2026-09-09 10:58:21 +00:00
Shllokkk
46c792f976 Merge pull request #58934 from frappe/mergify/bp/version-15-hotfix/pr-58897
fix: % Amount Billed exceeds 100% on fully rejected Purchase Receipts (backport #58897)
2026-09-09 15:33:07 +05:30
Shllokkk
c31ae577e4 fix: % Amount Billed exceeds 100% on fully rejected Purchase Receipts (#58897)
* fix: include rejected qty in Purchase Receipt billing base

* test: per billed stays 100% for fully rejected receipt

(cherry picked from commit 79c8e4db7f)
2026-09-09 09:34:29 +00:00
Frappe PR Bot
df8b7f9648 chore(release): Bumped to Version 15.121.2
## [15.121.2](https://github.com/frappe/erpnext/compare/v15.121.1...v15.121.2) (2026-09-09)

### Bug Fixes

* **stock:** preserve rates for unsaved mapped rows (backport [#58852](https://github.com/frappe/erpnext/issues/58852)) (backport [#58898](https://github.com/frappe/erpnext/issues/58898)) ([#58916](https://github.com/frappe/erpnext/issues/58916)) ([0deed27](0deed27cfe))
2026-09-09 09:24:59 +00:00
mergify[bot]
0deed27cfe fix(stock): preserve rates for unsaved mapped rows (backport #58852) (backport #58898) (#58916)
fix(stock): preserve rates for unsaved mapped rows (backport #58852) (#58898)

* fix: keep each row's own rate under maintain same rate

* test: cover maintain-same-rate rate lock for batch items

(cherry picked from commit 32d8c359ed)

Co-authored-by: Shllokkk <140623894+Shllokkk@users.noreply.github.com>
2026-09-09 14:53:20 +05:30
mergify[bot]
228108ad4c fix(accounts): stop counting received qty on non-stock invoice returns (backport #58924) (#58928)
Co-authored-by: Mihir Kandoi <kandoimihir@gmail.com>
2026-09-09 09:20:26 +00:00
Sudharsanan Ashok
75a5d2b766 Merge pull request #58920 from frappe/mergify/bp/version-15-hotfix/pr-58896
fix(stock): remove empty delivery stops after mapping (backport #58896)
2026-09-09 13:33:13 +05:30
Sudharsanan Ashok
27f93a83ef Merge pull request #58914 from frappe/mergify/bp/version-15-hotfix/pr-58911
fix: validate shelf life for automatically created expiring batches (backport #58911)
2026-09-09 13:24:59 +05:30
Sudharsanan Ashok
9822ffc334 Merge pull request #58912 from frappe/mergify/bp/version-15-hotfix/pr-58893
fix: reset price list fallback when changing parties (backport #58893)
2026-09-09 13:24:12 +05:30
Sudharsanan Ashok
fc6791e57b Merge pull request #58903 from frappe/mergify/bp/version-15-hotfix/pr-58889
fix(stock): guard inventory dimension lookup without reference document (backport #58889)
2026-09-09 13:23:46 +05:30
Sudharsanan Ashok
916b581562 Merge pull request #58900 from frappe/mergify/bp/version-15-hotfix/pr-58891
fix(accounts): reject disabled price lists in buying and selling (backport #58891)
2026-09-09 13:23:13 +05:30
Khushi Rawat
63e7c2e44f Merge pull request #58907 from frappe/mergify/bp/version-15-hotfix/pr-58227
fix: keep a dunning claimable until its interest is paid too  (backport #58227)
2026-09-09 13:09:48 +05:30
pandiyan
0099e7ec4f fix(stock): remove empty delivery stops after mapping (#58896)
Co-authored-by: Mihir Kandoi <kandoimihir@gmail.com>
(cherry picked from commit 4b23cee2ea)
2026-09-09 13:03:06 +05:30
pandiyan
11c6f0d02c fix: keep a dunning claimable until its interest is paid too
a dunning was resolved as soon as the invoiced sum was settled, because the
status was derived from the invoice outstanding alone. paying an invoice
without the interest and fee therefore closed the dunning and lost the
interest: a fresh dunning finds nothing overdue to charge it on.

the dunning amount is never a receivable, it only reaches the ledger as a
negative deduction on a payment entry made from the dunning. link that row
to the dunning so what has been collected is known, and resolve a dunning
only once the invoiced sum and the dunning amount are both paid. a dunning
resolved by hand keeps its status, so waiving the interest stays possible.

the deduction is a company currency field, so book and measure the dunning
amount through base_dunning_amount instead of the transaction currency one.

an interest-only payment leaves every invoice outstanding untouched, so
update the linked dunnings from the payment entry itself instead of relying
on the outstanding amount to change. such a payment also has to be built
from what is left to collect, not from the totals the dunning was raised
with, which are stale by then.

(cherry picked from commit d5a9d158f9)
2026-09-09 12:39:18 +05:30
pandiyan
da53283659 test: dunning must stay unpaid when only the invoiced sum is paid
paying a dunned invoice without its interest and fee marks the dunning
resolved, and the interest can no longer be collected.

(cherry picked from commit fa89552d10)
2026-09-09 12:39:18 +05:30
Shllokkk
32d8c359ed fix(stock): preserve rates for unsaved mapped rows (backport #58852) (#58898)
* fix: keep each row's own rate under maintain same rate

* test: cover maintain-same-rate rate lock for batch items
2026-09-09 12:38:58 +05:30
Pandiyan P
00e02f07ac fix: validate shelf life for automatically created expiring batches (#58911)
Co-authored-by: Ajish18 <ajishiyappan1@gmail.com>
(cherry picked from commit b2bdeaa672)
2026-09-09 07:07:22 +00:00
Pandiyan P
f981791012 fix: reset price list fallback when changing parties (#58893)
(cherry picked from commit 4c32acf300)
2026-09-09 06:56:26 +00:00
Sudharsanan Ashok
f6870786c5 Merge pull request #58888 from frappe/mergify/bp/version-15-hotfix/pr-58887
fix(stock): distribute additional costs when incoming items have no value (backport #58842) (backport #58887)
2026-09-09 11:14:21 +05:30
Sudharsanan11
00729a8d62 fix: resolve conflicts 2026-09-09 10:38:34 +05:30
Sudharsanan11
10987b11cc fix(stock): distribute additional costs when incoming items have no value
(cherry picked from commit b6035810f0)

# Conflicts:
#	erpnext/stock/doctype/stock_entry/test_stock_entry.py
2026-09-09 10:38:34 +05:30
pandiyan
47662b9af2 fix(accounts): reject disabled price lists in buying and selling (#58891)
(cherry picked from commit f8c2f3440b)
2026-09-09 09:55:37 +05:30
mergify[bot]
3bd194e986 fix: user not able to set valuation rate zero in stock reco (backport #58800) (#58821)
* fix: user not able to set valuation rate zero in stock reco (#58800)

* fix: user not able to set valuation rate zero in stock reco

* fix: wrong difference amount when valuation rate is zero

* fix: blank valuation rate should not be treated as a change

(cherry picked from commit e85e300f8f)

# Conflicts:
#	erpnext/stock/doctype/stock_reconciliation/test_stock_reconciliation.py

* chore: fix conflicts

Removed unused import statements and cleaned up the code.

---------

Co-authored-by: rohitwaghchaure <rohitw1991@gmail.com>
2026-09-09 04:20:51 +00:00
Pandiyan P
7ee54ba08b fix(stock): guard inventory dimension lookup without reference document (#58889)
Co-authored-by: Mihir Kandoi <kandoimihir@gmail.com>
(cherry picked from commit afd93cf867)
2026-09-09 02:12:59 +00:00
Sudharsanan Ashok
b6120ea56a Merge pull request #58882 from frappe/mergify/bp/version-15-hotfix/pr-58700
fix(stock): show actual outgoing rate in ledger preview (backport #58700)
2026-09-08 19:32:09 +05:30
Frappe PR Bot
fdc48277a8 chore(release): Bumped to Version 15.121.1
## [15.121.1](https://github.com/frappe/erpnext/compare/v15.121.0...v15.121.1) (2026-09-08)

### Bug Fixes

* **accounts:** reject same-account internal transfers ([#58529](https://github.com/frappe/erpnext/issues/58529)) ([05a1127](05a1127587))
* **accounts:** round journal entry totals to field precision (backport [#58629](https://github.com/frappe/erpnext/issues/58629)) ([#58874](https://github.com/frappe/erpnext/issues/58874)) ([96357b4](96357b4fdc))
* **accounts:** support drop-shipped items in Gross Profit report ([#58686](https://github.com/frappe/erpnext/issues/58686)) ([6c6ee7c](6c6ee7c524))
* add reconciliation after submit logic for bank transactions ([#57330](https://github.com/frappe/erpnext/issues/57330)) ([2ee5f6b](2ee5f6b1c4))
* **batch:** show Expired status only after expiry date has passed ([#58736](https://github.com/frappe/erpnext/issues/58736)) ([cd93007](cd93007780))
* check material request price list permission ([#58740](https://github.com/frappe/erpnext/issues/58740)) ([a348d41](a348d413d0))
* check write permission in whitelisted document methods (backport [#58689](https://github.com/frappe/erpnext/issues/58689)) ([#58702](https://github.com/frappe/erpnext/issues/58702)) ([baa30e7](baa30e703d))
* **crm:** check read permission on lead in add_lead_to_prospect ([4dd56ec](4dd56ec4e6))
* **crm:** validate contact email before saving an email campaign (backport [#58667](https://github.com/frappe/erpnext/issues/58667)) ([#58671](https://github.com/frappe/erpnext/issues/58671)) ([1ea597d](1ea597d6b5))
* fetch accounts by company (backport [#58523](https://github.com/frappe/erpnext/issues/58523)) ([#58878](https://github.com/frappe/erpnext/issues/58878)) ([2c2a3e9](2c2a3e9f10))
* filter cancelled BOMs in BOM Stock Analysis ([#58647](https://github.com/frappe/erpnext/issues/58647)) ([fff2616](fff261680c))
* **gross-profit:** include item_name in export ([#58631](https://github.com/frappe/erpnext/issues/58631)) ([c752bb3](c752bb34a8))
* include payment deductions in sales/purchase register ledger bal… (backport [#58437](https://github.com/frappe/erpnext/issues/58437)) ([#58679](https://github.com/frappe/erpnext/issues/58679)) ([24e7ff5](24e7ff55de))
* persist rendered terms on transaction save ([#58858](https://github.com/frappe/erpnext/issues/58858)) ([24cac30](24cac30aa9))
* **pos:** use company-currency change amount when netting pos gl entries (backport [#58599](https://github.com/frappe/erpnext/issues/58599)) ([#58677](https://github.com/frappe/erpnext/issues/58677)) ([c7d865e](c7d865ef3b))
* resolve conflicts ([95b2030](95b203079a))
* **selling:** fetch orders within billing allowance (backport [#58751](https://github.com/frappe/erpnext/issues/58751)) ([#58822](https://github.com/frappe/erpnext/issues/58822)) ([a64b78d](a64b78d283))
* **setup:** strict permissions for transaction deletion record (backport [#58687](https://github.com/frappe/erpnext/issues/58687)) ([#58722](https://github.com/frappe/erpnext/issues/58722)) ([934c7d8](934c7d833c))
* show cost center for unmatched payments in receivables (backport [#58453](https://github.com/frappe/erpnext/issues/58453)) ([#58880](https://github.com/frappe/erpnext/issues/58880)) ([69f38a0](69f38a04c8))
* skip zero quantity items in production plan material requests ([#58642](https://github.com/frappe/erpnext/issues/58642)) ([3217a69](3217a69fc2))
* **stock:** recalculate delivery note billing after return ([#58869](https://github.com/frappe/erpnext/issues/58869)) ([b409ded](b409ded2f6))

### Reverts

* **manufacturing:** remove material coverage changes on version 15 ([#58715](https://github.com/frappe/erpnext/issues/58715)) ([7cbf8b8](7cbf8b8660))
2026-09-08 13:48:11 +00:00
Diptanil Saha
8635652c90 Merge pull request #58867 from frappe/version-15-hotfix
chore: release v15
2026-09-08 19:16:20 +05:30
Afsal Syed
372244e6b2 fix(stock): show actual outgoing rate in ledger preview (#58700)
(cherry picked from commit 71f1edeb1c)
2026-09-08 19:11:06 +05:30
mergify[bot]
c7d865ef3b fix(pos): use company-currency change amount when netting pos gl entries (backport #58599) (#58677)
Co-authored-by: Vishnu Priya Baskaran <145791817+ervishnucs@users.noreply.github.com>
Co-authored-by: diptanilsaha <diptanil@frappe.io>
2026-09-08 13:23:45 +00:00
mergify[bot]
2c2a3e9f10 fix: fetch accounts by company (backport #58523) (#58878)
Co-authored-by: Vishnu Priya Baskaran <145791817+ervishnucs@users.noreply.github.com>
2026-09-08 18:18:36 +05:30
mergify[bot]
96357b4fdc fix(accounts): round journal entry totals to field precision (backport #58629) (#58874)
Co-authored-by: Sudharsanan Ashok <135326972+Sudharsanan11@users.noreply.github.com>
Co-authored-by: diptanilsaha <diptanil@frappe.io>
2026-09-08 12:47:54 +00:00
Sudharsanan Ashok
13367a5c54 Merge pull request #58872 from frappe/mergify/bp/version-15-hotfix/pr-58869
fix(stock): recalculate delivery note billing after return (backport #58869)
2026-09-08 18:10:08 +05:30
Sudharsanan Ashok
28918c8338 Merge pull request #58876 from frappe/mergify/bp/version-15-hotfix/pr-58529
fix(accounts): reject same-account internal transfers (backport #58529)
2026-09-08 18:09:11 +05:30
Sudharsanan Ashok
341089ce35 Merge pull request #58863 from frappe/mergify/bp/version-15-hotfix/pr-58631
fix(gross-profit): include item_name in export (backport #58631)
2026-09-08 18:05:08 +05:30
Sudharsanan Ashok
a8c6cec5a3 Merge pull request #58861 from frappe/mergify/bp/version-15-hotfix/pr-58858
fix: persist rendered terms on transaction save (backport #58858)
2026-09-08 18:04:24 +05:30
Sudharsanan Ashok
89b29eee94 Merge pull request #58762 from frappe/mergify/bp/version-15-hotfix/pr-57330
fix: add reconciliation after submit logic for bank transactions (backport #57330)
2026-09-08 18:02:38 +05:30
Pandiyan P
b409ded2f6 fix(stock): recalculate delivery note billing after return (#58869)
(cherry picked from commit f864333afa)

# Conflicts:
#	erpnext/stock/doctype/delivery_note/services/billing_status.py
2026-09-08 17:38:48 +05:30
mergify[bot]
69f38a04c8 fix: show cost center for unmatched payments in receivables (backport #58453) (#58880)
Co-authored-by: Krishna Pramod Shirsath <91021227+krishna-254@users.noreply.github.com>
2026-09-08 17:33:31 +05:30
Pandiyan P
05a1127587 fix(accounts): reject same-account internal transfers (#58529)
(cherry picked from commit 36a4dfe797)

# Conflicts:
#	erpnext/accounts/doctype/payment_entry/test_payment_entry.py
2026-09-08 16:51:53 +05:30
Sudharsanan Ashok
940fda3327 Merge pull request #58859 from frappe/mergify/bp/version-15-hotfix/pr-58841
fix: skip zero quantity items in production plan material requests (backport #58841)
2026-09-08 15:59:18 +05:30
Sudharsanan11
95b203079a fix: resolve conflicts 2026-09-08 15:21:30 +05:30
Vishnu Priya Baskaran
c752bb34a8 fix(gross-profit): include item_name in export (#58631)
(cherry picked from commit 467f54162f)
2026-09-08 09:13:58 +00:00
Pandiyan P
24cac30aa9 fix: persist rendered terms on transaction save (#58858)
(cherry picked from commit cadc0ca86d)
2026-09-08 07:58:53 +00:00
Mihir Kandoi
a64b78d283 fix(selling): fetch orders within billing allowance (backport #58751) (#58822) 2026-09-08 09:16:56 +05:30
Mihir Kandoi
4a3a2cbdc4 test(stock): use existing warehouse fixtures in Pick List tests (v15) (#58840) 2026-09-07 15:22:12 +00:00
Mihir Kandoi
6c6ee7c524 fix(accounts): support drop-shipped items in Gross Profit report (#58686)
* fix(reports): apportion drop-ship buying cost and fix return-matching bug in Gross Profit report

* test(accounts): fix Gross Profit test setup

---------

Co-authored-by: ervishnucs <ervishnucs369@gmail.com>
2026-09-07 15:52:57 +05:30
rohitwaghchaure
baa30e703d fix: check write permission in whitelisted document methods (backport #58689) (#58702)
* fix: check write permission in whitelisted document methods

* test: permission coverage for production plan status roll-ups

* fix: add type hints to whitelisted arguments and submit MR in test

* test: clear request cache before reading non-completed production plans
2026-09-07 15:20:22 +05:30
Mihir Kandoi
684def8818 test(manufacturing): refresh cached production plans before assertion (#58801) 2026-09-07 09:13:45 +00:00
Vishnu Priya Baskaran
2ee5f6b1c4 fix: add reconciliation after submit logic for bank transactions (#57330)
Co-authored-by: Poovetha <poovethapalanivelu@gmail.com>
(cherry picked from commit c3319d74cf)
2026-09-04 11:35:56 +00:00
Mihir Kandoi
7cbf8b8660 revert(manufacturing): remove material coverage changes on version 15 (#58715) 2026-09-04 14:32:57 +05:30
Sudharsanan Ashok
0611a6a12b Merge pull request #58753 from frappe/mergify/bp/version-15-hotfix/pr-58740
fix: check material request price list permission (backport #58740)
2026-09-04 13:07:44 +05:30
Pandiyan P
a348d413d0 fix: check material request price list permission (#58740)
(cherry picked from commit 0b1f1d6851)
2026-09-04 07:33:07 +00:00
Sudharsanan Ashok
452db26ccb Merge pull request #58748 from frappe/mergify/bp/version-15-hotfix/pr-58736
fix(batch): show Expired status only after expiry date has passed (backport #58736)
2026-09-04 13:00:37 +05:30
mergify[bot]
934c7d833c fix(setup): strict permissions for transaction deletion record (backport #58687) (#58722)
Co-authored-by: Diptanil Saha <diptanil@frappe.io>
2026-09-04 06:53:44 +00:00
Pandiyan P
cd93007780 fix(batch): show Expired status only after expiry date has passed (#58736)
Co-authored-by: Ajish18 <ajishiyappan1@gmail.com>
(cherry picked from commit 00f04fc084)
2026-09-04 06:51:10 +00:00
mergify[bot]
24e7ff55de fix: include payment deductions in sales/purchase register ledger bal… (backport #58437) (#58679)
Co-authored-by: Vishnu Priya Baskaran <145791817+ervishnucs@users.noreply.github.com>
2026-09-02 17:01:20 +05:30
Shllokkk
5f647f0702 Merge pull request #58690 from frappe/mergify/bp/version-15-hotfix/pr-58684
fix(crm): check read permission on lead in add_lead_to_prospect (backport #58684)
2026-09-02 16:01:56 +05:30
Krishna Pramod Shirsath
7ab4092561 Merge pull request #58695 from frappe/mergify/bp/version-15-hotfix/pr-58647
fix: filter cancelled BOMs in BOM Stock Analysis (backport #58647)
2026-09-02 15:31:03 +05:30
Krishna Pramod Shirsath
fff261680c fix: filter cancelled BOMs in BOM Stock Analysis (#58647)
(cherry picked from commit a2071a6fdd)

# Conflicts:
#	erpnext/manufacturing/report/bom_stock_analysis/bom_stock_analysis.js
2026-09-02 09:59:16 +00:00
mergify[bot]
1ea597d6b5 fix(crm): validate contact email before saving an email campaign (backport #58667) (#58671)
Co-authored-by: kaulith <64089478+kaulith@users.noreply.github.com>
2026-09-02 15:12:57 +05:30
Shllokkk
4dd56ec4e6 fix(crm): check read permission on lead in add_lead_to_prospect
(cherry picked from commit 02fcdc0337)

# Conflicts:
#	erpnext/crm/doctype/lead/lead.py
2026-09-02 15:01:41 +05:30
Krishna Pramod Shirsath
3217a69fc2 fix: skip zero quantity items in production plan material requests (#58642) 2026-09-02 13:32:41 +05:30
Frappe PR Bot
1a0bf0bf6c chore(release): Bumped to Version 15.121.0
# [15.121.0](https://github.com/frappe/erpnext/compare/v15.120.0...v15.121.0) (2026-09-02)

### Bug Fixes

* **accounts:** set pos profile on invoices respecting user permissions (backport [#58508](https://github.com/frappe/erpnext/issues/58508)) ([#58518](https://github.com/frappe/erpnext/issues/58518)) ([1187fb8](1187fb8e01))
* **accounts:** validate frozen accounts in period closing voucher ([#58477](https://github.com/frappe/erpnext/issues/58477)) ([045d708](045d7086d1))
* add missing perm checks on various whitelisted methods (backport [#58652](https://github.com/frappe/erpnext/issues/58652)) ([#58653](https://github.com/frappe/erpnext/issues/58653)) ([547d82d](547d82da56))
* add type hints to make_request_for_quotation ([567730e](567730e38e))
* **bank_statement_import:** add missing permission check on multiple whitelisted methods (backport [#58221](https://github.com/frappe/erpnext/issues/58221)) ([#58223](https://github.com/frappe/erpnext/issues/58223)) ([fa903f4](fa903f40fd))
* clarify duplicate internal party messages ([#58469](https://github.com/frappe/erpnext/issues/58469)) ([17208e7](17208e7434))
* **company:** throw if linked to demo_company field ([de260bd](de260bd43c))
* **crm:** add missing permission validation on `get_contract_template` (backport [#58621](https://github.com/frappe/erpnext/issues/58621)) ([#58622](https://github.com/frappe/erpnext/issues/58622)) ([d1b615b](d1b615b851))
* **crm:** check write permission in edit_note ([2b2a005](2b2a005682))
* do not map the same row twice in "Get Items From" (backport [#58617](https://github.com/frappe/erpnext/issues/58617)) ([#58618](https://github.com/frappe/erpnext/issues/58618)) ([28175a5](28175a5c9d))
* filter fully ordered items when creating RFQ from Material Request ([08ec311](08ec31174c))
* keep Currency and Price List section open for foreign currency (backport [#58074](https://github.com/frappe/erpnext/issues/58074)) ([#58112](https://github.com/frappe/erpnext/issues/58112)) ([f5ce20f](f5ce20f122))
* keep source rate on re-fetch when maintain same rate is enabled (backport [#57479](https://github.com/frappe/erpnext/issues/57479)) ([#58332](https://github.com/frappe/erpnext/issues/58332)) ([228ab2d](228ab2d97e)), closes [frappe/erpnext#57436](https://github.com/frappe/erpnext/issues/57436)
* **manufacturing:** preserve job card qty in mr transfer (backport [#58482](https://github.com/frappe/erpnext/issues/58482)) ([#58498](https://github.com/frappe/erpnext/issues/58498)) ([099a5a7](099a5a71d9))
* **manufacturing:** use packed row delivery date ([#58569](https://github.com/frappe/erpnext/issues/58569)) ([9c19b02](9c19b024db))
* mark item tax templates as not applicable (backport [#54673](https://github.com/frappe/erpnext/issues/54673)) (backport [#54677](https://github.com/frappe/erpnext/issues/54677)) ([#58462](https://github.com/frappe/erpnext/issues/58462)) ([d62f6e7](d62f6e715f))
* persist redistributed additional costs during stock entry repost (backport [#58433](https://github.com/frappe/erpnext/issues/58433)) ([#58532](https://github.com/frappe/erpnext/issues/58532)) ([c4e7cfa](c4e7cfa6a0))
* **projects:** check read permission on source in create_duplicate_project ([af8c010](af8c010aa8))
* **projects:** ignore cancelled invoices in timesheet portal (backport [#58501](https://github.com/frappe/erpnext/issues/58501)) ([#58503](https://github.com/frappe/erpnext/issues/58503)) ([5a51895](5a518951e4))
* reset hardcoded letter head on Incorrect Serial and Batch Bundle report ([ccdaa92](ccdaa92de8))
* resolve analytics backport conflicts ([605918d](605918d3a2))
* resolve conflicts ([c6717fb](c6717fb758))
* resolve stock entry backport conflicts ([e126c45](e126c4597b))
* round party balances to currency precision in Trial Balance for Party ([b98d193](b98d193b77))
* **selling:** check quotation write permission before marking lost ([#58493](https://github.com/frappe/erpnext/issues/58493)) ([33ebc7d](33ebc7d7e3))
* **selling:** check sales order permission before work order creation ([#58492](https://github.com/frappe/erpnext/issues/58492)) ([0609b06](0609b06564))
* **sms_settings:** add patch to pre-fill roles into SMS Settings Roles Table ([0cef90d](0cef90d079))
* **stock:** keep pick list links when refetching stock entry items ([22377fa](22377fa86d))
* **stock:** load available serial no report (backport [#58558](https://github.com/frappe/erpnext/issues/58558)) ([#58561](https://github.com/frappe/erpnext/issues/58561)) ([2d46bb9](2d46bb962c))
* **stock:** preserve exchange gain loss journals in lcv ([#58505](https://github.com/frappe/erpnext/issues/58505)) ([c6fedf4](c6fedf4aca))
* **stock:** reset bin when a repost finds no stock ledger entries  ([#58434](https://github.com/frappe/erpnext/issues/58434)) ([b00062d](b00062df86)), closes [#58362](https://github.com/frappe/erpnext/issues/58362)
* **stock:** validate serial inventory dimensions ([#58394](https://github.com/frappe/erpnext/issues/58394)) ([bc071d7](bc071d7793))
* sum item and its alternate transferred qty on work order required items ([5851bb3](5851bb3b6e))
* **taxes:** skip tax addition for invoice created from opening invoice tool ([7090c6f](7090c6fdab))
* **timesheet:** scoping whitelisted methods output to projects and timesheets that are acccessible to users (backport [#58267](https://github.com/frappe/erpnext/issues/58267)) ([#58576](https://github.com/frappe/erpnext/issues/58576)) ([c656497](c656497aac))
* translate doctype in map msg (backport [#58515](https://github.com/frappe/erpnext/issues/58515)) ([#58516](https://github.com/frappe/erpnext/issues/58516)) ([d87a4b2](d87a4b2541))
* translate label in party validation (backport [#58624](https://github.com/frappe/erpnext/issues/58624)) ([#58625](https://github.com/frappe/erpnext/issues/58625)) ([307ffcd](307ffcd5c3))
* validate items against source Sales Order in Material Request ([32d44c6](32d44c6e91))
* validate POS Settings invoice and search fields on the server (backport [#58611](https://github.com/frappe/erpnext/issues/58611)) ([#58612](https://github.com/frappe/erpnext/issues/58612)) ([c5bc5f9](c5bc5f9c31))
* Work Order picks wrong Delivery Date when Sales Order has the same item in multiple rows ([#58527](https://github.com/frappe/erpnext/issues/58527)) ([7454735](7454735595))

### Features

* **analytics:** filter sales and purchase analytics by entity ([#58402](https://github.com/frappe/erpnext/issues/58402)) ([0dddd00](0dddd00073))
2026-09-02 07:16:53 +00:00
Diptanil Saha
57266ab474 Merge pull request #58646 from frappe/version-15-hotfix
chore: release v15
2026-09-02 12:45:04 +05:30
Shllokkk
865b207340 Merge pull request #58676 from frappe/mergify/bp/version-15-hotfix/pr-58535
fix: filter fully ordered items when creating RFQ from Material Request (backport #58535)
2026-09-02 12:19:57 +05:30
Sudharsanan Ashok
05199aa3bb Merge pull request #58674 from frappe/mergify/bp/version-15-hotfix/pr-58505
fix(stock): preserve exchange gain loss journals in lcv (backport #58505)
2026-09-02 12:13:02 +05:30
Shllokkk
4a4e1908e3 chore: resolve backport conflict 2026-09-02 11:50:21 +05:30
Shllokkk
b439deda88 test: set schedule date on PO before insert
(cherry picked from commit 5af60cf2e3)
2026-09-02 06:16:30 +00:00
Shllokkk
567730e38e fix: add type hints to make_request_for_quotation
(cherry picked from commit 4435f166ea)
2026-09-02 06:16:30 +00:00
Shllokkk
3d563a2e08 test: RFQ from Material Request skips fully ordered items
(cherry picked from commit 5adcb28b3c)

# Conflicts:
#	erpnext/stock/doctype/material_request/test_material_request.py
2026-09-02 06:16:29 +00:00
Shllokkk
08ec31174c fix: filter fully ordered items when creating RFQ from Material Request
(cherry picked from commit 9b1d907b6a)
2026-09-02 06:16:29 +00:00
Pandiyan P
c6fedf4aca fix(stock): preserve exchange gain loss journals in lcv (#58505)
(cherry picked from commit 2b54a581f8)
2026-09-02 06:14:58 +00:00
mergify[bot]
547d82da56 fix: add missing perm checks on various whitelisted methods (backport #58652) (#58653)
Co-authored-by: Diptanil Saha <diptanil@frappe.io>
2026-09-01 14:16:38 +00:00
Shllokkk
d704dc474e Merge pull request #58648 from frappe/mergify/bp/version-15-hotfix/pr-58607
fix: round party balances to currency precision in Trial Balance for Party (backport #58607)
2026-09-01 16:42:52 +05:30
Aarol D'Souza
46a99ec216 Merge pull request #58636 from frappe/mergify/bp/version-15-hotfix/pr-58586
fix(sms_settings): add patch to pre-fill roles into SMS Settings Role Table (backport #58586)
2026-09-01 15:46:14 +05:30
Shllokkk
b98d193b77 fix: round party balances to currency precision in Trial Balance for Party
(cherry picked from commit b1c7657dfa)
2026-09-01 09:49:32 +00:00
Diptanil Saha
5289982059 fix(accounts)!: add permission checks on payment entry whitelisted methods (#58643) 2026-09-01 15:17:57 +05:30
AarDG10
2f2a9301d8 chore: resolve conflicts 2026-09-01 12:55:27 +05:30
AarDG10
0cef90d079 fix(sms_settings): add patch to pre-fill roles into SMS Settings Roles Table
(cherry picked from commit 3501beb2bd)

# Conflicts:
#	erpnext/patches.txt
2026-09-01 07:18:22 +00:00
mergify[bot]
307ffcd5c3 fix: translate label in party validation (backport #58624) (#58625)
Co-authored-by: Raffael Meyer <14891507+barredterra@users.noreply.github.com>
2026-09-01 00:54:08 +02:00
mergify[bot]
d1b615b851 fix(crm): add missing permission validation on get_contract_template (backport #58621) (#58622)
Co-authored-by: Diptanil Saha <diptanil@frappe.io>
2026-08-31 19:49:07 +00:00
mergify[bot]
fa903f40fd fix(bank_statement_import): add missing permission check on multiple whitelisted methods (backport #58221) (#58223)
Co-authored-by: Diptanil Saha <diptanil@frappe.io>
2026-08-31 19:39:12 +00:00
Diptanil Saha
c5bc5f9c31 fix: validate POS Settings invoice and search fields on the server (backport #58611) (#58612) 2026-08-31 18:39:27 +00:00
mergify[bot]
28175a5c9d fix: do not map the same row twice in "Get Items From" (backport #58617) (#58618)
Co-authored-by: Raffael Meyer <14891507+barredterra@users.noreply.github.com>
2026-08-31 19:00:31 +02:00
Lakshit Jain
4cff4b7cec Merge pull request #58601 from frappe/mergify/bp/version-15-hotfix/pr-58483
fix(taxes): skip tax addition for invoice created from opening invoice tool (backport #58483)
2026-08-31 18:39:01 +05:30
ljain112
4ad0180dff chore: resolve conflicts 2026-08-31 17:20:46 +05:30
ljain112
eed5969c28 chore: resolve conflicts 2026-08-31 17:08:48 +05:30
ljain112
ae01c21614 chore: resolve conflicts 2026-08-31 16:56:39 +05:30
ljain112
7090c6fdab fix(taxes): skip tax addition for invoice created from opening invoice tool
(cherry picked from commit e08a166281)

# Conflicts:
#	erpnext/accounts/doctype/opening_invoice_creation_tool/test_opening_invoice_creation_tool.py
#	erpnext/accounts/services/taxes.py
2026-08-31 09:35:34 +00:00
Nishka Gosalia
0f84b25964 Merge pull request #58593 from frappe/mergify/bp/version-15-hotfix/pr-58325
fix(projects): check read permission on source in create_duplicate_project (backport #58325)
2026-08-31 14:31:04 +05:30
Shllokkk
0ea03a688b chore(projects): add type hints to create_duplicate_project 2026-08-31 14:04:32 +05:30
Shllokkk
af8c010aa8 fix(projects): check read permission on source in create_duplicate_project
(cherry picked from commit 8c8b282a2e)
2026-08-31 07:11:10 +00:00
mergify[bot]
c656497aac fix(timesheet): scoping whitelisted methods output to projects and timesheets that are acccessible to users (backport #58267) (#58576)
Co-authored-by: Diptanil Saha <diptanil@frappe.io>
2026-08-30 18:36:29 +00:00
Mihir Kandoi
9c19b024db fix(manufacturing): use packed row delivery date (#58569) 2026-08-30 11:14:14 +00:00
Henil Maru
7454735595 fix: Work Order picks wrong Delivery Date when Sales Order has the same item in multiple rows (#58527) 2026-08-30 15:56:38 +05:30
mergify[bot]
2d46bb962c fix(stock): load available serial no report (backport #58558) (#58561)
fix(stock): load available serial no report (#58558)

(cherry picked from commit 8b43394533)

Co-authored-by: Pandiyan P <pandiyanpalani37@gmail.com>
2026-08-29 14:56:06 +00:00
mergify[bot]
6a632d6d1c refactor(stock): remove dead warehouse_condition branch on get_stock_ledger_entries (backport #58552) (#58553)
Co-authored-by: Diptanil Saha <diptanil@frappe.io>
2026-08-29 17:55:45 +05:30
Shllokkk
e19686053f Merge pull request #58543 from frappe/mergify/bp/version-15-hotfix/pr-58324
fix(crm): check write permission in edit_note (backport #58324)
2026-08-29 13:28:02 +05:30
Shllokkk
f0ac82605c chore: resolve merge conflicts 2026-08-29 13:08:42 +05:30
Shllokkk
2b2a005682 fix(crm): check write permission in edit_note
(cherry picked from commit eb49f51d29)

# Conflicts:
#	erpnext/crm/utils.py
2026-08-28 15:05:16 +00:00
mergify[bot]
c4e7cfa6a0 fix: persist redistributed additional costs during stock entry repost (backport #58433) (#58532)
* fix: persist redistributed additional costs during stock entry repost (#58433)

* fix: persist redistributed additional costs during stock entry repost

* test: cover additional cost persistence on stock entry recalculation

(cherry picked from commit 074c84e880)

# Conflicts:
#	erpnext/stock/doctype/repost_item_valuation/test_repost_item_valuation.py

* chore: fix conflicts

Removed unused import 'flt' from test file.

---------

Co-authored-by: Afsal Syed <146159709+Afsalsyed@users.noreply.github.com>
Co-authored-by: rohitwaghchaure <rohitw1991@gmail.com>
2026-08-28 10:42:27 +00:00
Sudharsanan Ashok
1aa7528119 Merge pull request #58494 from frappe/mergify/bp/version-15-hotfix/pr-58493
fix(selling): check quotation write permission before marking lost (backport #58493)
2026-08-28 13:29:46 +05:30
Sudharsanan Ashok
1a92047887 Merge pull request #58496 from frappe/mergify/bp/version-15-hotfix/pr-58492
fix(selling): check sales order permission before work order creation (backport #58492)
2026-08-28 13:15:00 +05:30
pandiyan
33ebc7d7e3 fix(selling): check quotation write permission before marking lost (#58493)
(cherry picked from commit 5f99a3418d)

# Conflicts:
#	erpnext/selling/doctype/quotation/quotation.py
2026-08-28 13:04:34 +05:30
pandiyan
0609b06564 fix(selling): check sales order permission before work order creation (#58492)
(cherry picked from commit a8ba713f80)

# Conflicts:
#	erpnext/selling/doctype/sales_order/mapper.py
2026-08-28 12:55:57 +05:30
Shllokkk
b8163e271d Merge pull request #58500 from Shllokkk/work-order-transferred-qty-sum-alternate-items
fix: sum item and its alternate transferred qty on work order
2026-08-28 12:47:53 +05:30
Aarol D'Souza
44cb0c5141 Merge pull request #58426 from frappe/mergify/bp/version-15-hotfix/pr-58351
fix(company): throw if linked to demo_company field (backport #58351)
2026-08-28 12:14:29 +05:30
mergify[bot]
1187fb8e01 fix(accounts): set pos profile on invoices respecting user permissions (backport #58508) (#58518)
Co-authored-by: Diptanil Saha <diptanil@frappe.io>
2026-08-28 06:42:02 +00:00
Aarol D'Souza
be0fc95758 Merge branch 'version-15-hotfix' into mergify/bp/version-15-hotfix/pr-58351 2026-08-28 11:48:39 +05:30
AarDG10
3edd8ee8be refactor: remove bold from formatter 2026-08-28 11:48:07 +05:30
Sudharsanan Ashok
d5318fbabc Merge pull request #58522 from frappe/mergify/bp/version-15-hotfix/pr-58521
Revert "refactor(stock): use db.count for the empty ledger check (backport #58486)" (backport #58521)
2026-08-27 23:10:06 +05:30
mergify[bot]
d87a4b2541 fix: translate doctype in map msg (backport #58515) (#58516)
Co-authored-by: Raffael Meyer <14891507+barredterra@users.noreply.github.com>
2026-08-27 19:26:19 +02:00
Sudharsanan11
c6717fb758 fix: resolve conflicts 2026-08-27 22:51:14 +05:30
Sudharsanan Ashok
0e7be81f86 Revert "refactor(stock): use db.count for the empty ledger check (backport #58486)"
(cherry picked from commit 8287906a71)

# Conflicts:
#	erpnext/stock/stock_ledger.py
2026-08-27 17:16:30 +00:00
mergify[bot]
5a518951e4 fix(projects): ignore cancelled invoices in timesheet portal (backport #58501) (#58503)
Co-authored-by: Mihir Kandoi <kandoimihir@gmail.com>
2026-08-27 13:24:40 +00:00
Mihir Kandoi
099a5a71d9 fix(manufacturing): preserve job card qty in mr transfer (backport #58482) (#58498) 2026-08-27 12:39:48 +00:00
Shllokkk
70dff35736 test: transferred qty sums item and its alternate 2026-08-27 17:54:07 +05:30
Shllokkk
5851bb3b6e fix: sum item and its alternate transferred qty on work order required items 2026-08-27 17:47:05 +05:30
Sudharsanan Ashok
b00062df86 fix(stock): reset bin when a repost finds no stock ledger entries (#58434)
* fix(stock): reset bin when a repost finds no stock ledger entries

`build()` wipes `prev_sle_dict` in `initialize_reposting()` before `update_bin()`
runs, so a repost over an item and warehouse whose ledger is empty writes no bin
at all. `actual_qty`, `stock_value` and `valuation_rate` keep their last values,
bin totals drift from the stock balance, and reposting again cannot heal it.

Reset those bins as a terminal step in `update_bin()`, guarded by a re-check that
no live SLE exists so ordinary valuation is untouched.

Cancel is already correct on this branch, since `initialize_previous_data()` seeds
zeros when there is no previous SLE and the sle_id path never calls
`initialize_reposting()`. That seeding stays; this is a repost-path fix only.
develop drops it in #58362 because the `cancelled` guard makes it dead code there.

* test(stock): cover bin reset when the stock ledger is empty
2026-08-27 16:23:10 +05:30
Sudharsanan Ashok
2ce0bb1009 Merge pull request #58474 from frappe/mergify/bp/version-15-hotfix/pr-58469
fix: clarify duplicate internal party messages (backport #58469)
2026-08-27 16:13:40 +05:30
Sudharsanan Ashok
25ec044c09 Merge pull request #58428 from frappe/mergify/bp/version-15-hotfix/pr-58402
feat(analytics): filter sales and purchase analytics by entity  (backport #58402)
2026-08-27 16:12:13 +05:30
Aarol D'Souza
81cf874fd7 Merge branch 'version-15-hotfix' into mergify/bp/version-15-hotfix/pr-58351 2026-08-27 15:42:27 +05:30
mergify[bot]
d62f6e715f fix: mark item tax templates as not applicable (backport #54673) (backport #54677) (#58462)
Co-authored-by: Raffael Meyer <14891507+barredterra@users.noreply.github.com>
2026-08-27 09:46:30 +00:00
Pandiyan P
045d7086d1 fix(accounts): validate frozen accounts in period closing voucher (#58477) 2026-08-27 08:46:01 +00:00
Shllokkk
6f95c1ff92 Merge pull request #58473 from frappe/mergify/bp/version-15-hotfix/pr-58470
fix: validate items against source Sales Order in Material Request (backport #58470)
2026-08-27 14:04:44 +05:30
pandiyan
17208e7434 fix: clarify duplicate internal party messages (#58469)
(cherry picked from commit 4d4cf034b5)

# Conflicts:
#	erpnext/selling/doctype/customer/customer.py
2026-08-27 13:53:43 +05:30
Shllokkk
59a9819dae test: block item change on Sales Order-sourced Material Request row
(cherry picked from commit 07f8250e40)

# Conflicts:
#	erpnext/stock/doctype/material_request/test_material_request.py
2026-08-27 13:17:29 +05:30
Shllokkk
32d44c6e91 fix: validate items against source Sales Order in Material Request
(cherry picked from commit 65466464df)
2026-08-27 07:36:46 +00:00
Sudharsanan11
605918d3a2 fix: resolve analytics backport conflicts 2026-08-26 16:10:56 +05:30
Sudharsanan Ashok
0dddd00073 feat(analytics): filter sales and purchase analytics by entity (#58402)
Co-authored-by: Mihir Kandoi <kandoimihir@gmail.com>
(cherry picked from commit 3f29cdf8d2)

# Conflicts:
#	erpnext/buying/report/purchase_analytics/purchase_analytics.js
#	erpnext/buying/report/purchase_analytics/test_purchase_analytics.py
#	erpnext/selling/report/sales_analytics/sales_analytics.py
#	erpnext/selling/report/sales_analytics/test_sales_analytics.py
2026-08-26 16:10:56 +05:30
Shllokkk
3bf19df761 Merge pull request #58440 from Shllokkk/incorrect-serial-batch-bundle-letter-head
fix: reset hardcoded letter head on Incorrect Serial and Batch Bundle report
2026-08-26 15:49:34 +05:30
Shllokkk
ccdaa92de8 fix: reset hardcoded letter head on Incorrect Serial and Batch Bundle report 2026-08-26 14:50:32 +05:30
Sudharsanan Ashok
6d59065d79 Merge pull request #58424 from frappe/mergify/bp/version-15-hotfix/pr-58405
fix(stock): keep pick list links when refetching stock entry items (backport #58374) (backport #58405)
2026-08-26 13:40:13 +05:30
Jatin3128
228ab2d97e fix: keep source rate on re-fetch when maintain same rate is enabled (backport #57479) (#58332)
* fix: keep source rate on re-fetch when maintain same rate is enabled (backport #57479)

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, both for a single-row re-fetch and the bulk
apply_price_list path (price list / party / conversion rate change).

The rate is read from the linked source row in the database (not the mutable
target row) and permission-checked against the source document, so an unsaved
edit can't lock in a different rate and a crafted request can't disclose
another document's pricing.

Fixes frappe/erpnext#57436

* fix: resolve linter findings in get_item_details

Add missing type hints on the whitelisted get_item_details
signature and rename maintain_same_rate_enabled's sole "args"
parameter, both flagged by the semgrep security/code-quality
rules. Also drops an extra blank line that ruff-format rejected.

* fix: widen get_item_details doc type hint to include Document

accounts_controller.py calls get_item_details(args, self, ...)
during validate, passing the transaction Document itself, not
a dict/JSON string. The narrower hint tripped Frappe's runtime
argument type validation on every whitelisted call with a live
Document, failing test-record creation across the suite.
2026-08-26 13:14:25 +05:30
Sudharsanan11
e126c4597b fix: resolve stock entry backport conflicts 2026-08-26 13:09:08 +05:30
Sudharsanan11
22377fa86d fix(stock): keep pick list links when refetching stock entry items
(cherry picked from commit 01e0844d40)

# Conflicts:
#	erpnext/stock/doctype/stock_entry/stock_entry.js
2026-08-26 13:09:08 +05:30
AarDG10
de260bd43c fix(company): throw if linked to demo_company field
Throws an error msg if user is deleting demo company directly.

(cherry picked from commit aaa3100efc)
2026-08-26 07:24:05 +00:00
Sudharsanan Ashok
9e082a96f7 Merge pull request #58418 from frappe/mergify/bp/version-15-hotfix/pr-58394
fix(stock): validate serial inventory dimensions (backport #58394)
2026-08-26 12:53:35 +05:30
Pandiyan P
bc071d7793 fix(stock): validate serial inventory dimensions (#58394)
* fix(stock): validate serial inventory dimensions

* test(stock): cover serial inventory dimensions

(cherry picked from commit c940bd1e66)

# Conflicts:
#	erpnext/stock/doctype/inventory_dimension/test_inventory_dimension.py
#	erpnext/stock/doctype/stock_ledger_entry/stock_ledger_entry.py
2026-08-26 12:28:31 +05:30
mergify[bot]
f5ce20f122 fix: keep Currency and Price List section open for foreign currency (backport #58074) (#58112)
* 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.

(cherry picked from commit 4a8342496e)

# Conflicts:
#	erpnext/accounts/doctype/pos_invoice/pos_invoice.json
#	erpnext/accounts/doctype/sales_invoice/sales_invoice.json
#	erpnext/buying/doctype/purchase_order/purchase_order.json
#	erpnext/buying/doctype/supplier_quotation/supplier_quotation.json
#	erpnext/selling/doctype/sales_order/sales_order.json
#	erpnext/stock/doctype/delivery_note/delivery_note.json
#	erpnext/stock/doctype/purchase_receipt/purchase_receipt.json

* fix: resolve unresolved cherry-pick conflict markers in modified timestamps

Mergify's automatic cherry-pick of #58074 left conflict markers
committed on the modified field, breaking JSON parsing.

---------

Co-authored-by: Jatin3128 <140256508+Jatin3128@users.noreply.github.com>
Co-authored-by: Jatin3128 <jatinsarna8@gmail.com>
2026-08-26 11:35:24 +05:30
Frappe PR Bot
945e825bee chore(release): Bumped to Version 15.120.0
# [15.120.0](https://github.com/frappe/erpnext/compare/v15.119.3...v15.120.0) (2026-08-25)

### Bug Fixes

* **accounts:** disallow reversing a reverse journal entry ([15041a6](15041a62dd))
* **accounts:** supplier group filter not applied on accounts payable report ([743f7d8](743f7d8713))
* aggregate child warehouses in Stock Qty vs Serial No Count report (backport [#58134](https://github.com/frappe/erpnext/issues/58134)) ([#58365](https://github.com/frappe/erpnext/issues/58365)) ([61238e7](61238e7c4c))
* allow custom remark on reversal journal entry ([#58308](https://github.com/frappe/erpnext/issues/58308)) ([b578fb5](b578fb52d5))
* asset scrap flow related changes (backport [#55126](https://github.com/frappe/erpnext/issues/55126)) ([#58144](https://github.com/frappe/erpnext/issues/58144)) ([167cc1e](167cc1e5b9))
* **assets:** split FIFO/LIFO rate across grouped stock item rows ([c2c4e5e](c2c4e5ee8b))
* attributeerror on budget against a non profit and loss account ([2095411](2095411a28))
* **bank_statement_import:** add missing permission check on `get_import_status` (backport [#58217](https://github.com/frappe/erpnext/issues/58217)) ([#58218](https://github.com/frappe/erpnext/issues/58218)) ([1464a34](1464a34fc6))
* block disabled/frozen party on Opportunity and Request for Quotation (backport [#57983](https://github.com/frappe/erpnext/issues/57983)) ([#58034](https://github.com/frappe/erpnext/issues/58034)) ([88a36a8](88a36a800a))
* **buying:** allow purchase returns against a closed purchase order ([#58140](https://github.com/frappe/erpnext/issues/58140)) ([81c5393](81c53931b5))
* correct Item Group doctype name in item tax template dashboard  (backport [#58192](https://github.com/frappe/erpnext/issues/58192)) ([#58212](https://github.com/frappe/erpnext/issues/58212)) ([46d883d](46d883d00d))
* **crm_settings:** create custom fields for Frappe CRM on enabling synchronization ([eb85ca6](eb85ca68f6))
* don't set work order status to In Process only due to skip material transfer ([#58246](https://github.com/frappe/erpnext/issues/58246)) ([73b7ec3](73b7ec32b6))
* drop removed Restaurant doctype from sales tax template dashboard  (backport [#58191](https://github.com/frappe/erpnext/issues/58191)) ([#58210](https://github.com/frappe/erpnext/issues/58210)) ([32a5b23](32a5b23b3c))
* **email_digest:** added permission check for `get_msg_html` (backport [#58197](https://github.com/frappe/erpnext/issues/58197)) ([#58199](https://github.com/frappe/erpnext/issues/58199)) ([c6211eb](c6211eb075))
* escape interpolated values in portal, print and desk templates (backport [#58273](https://github.com/frappe/erpnext/issues/58273)) ([#58277](https://github.com/frappe/erpnext/issues/58277)) ([37f2770](37f2770809))
* escape interpolated values in text positions across portal and desk templates (backport [#58286](https://github.com/frappe/erpnext/issues/58286)) ([#58287](https://github.com/frappe/erpnext/issues/58287)) ([1210c61](1210c6187d))
* escape on status image for workstations in production status (backport [#58279](https://github.com/frappe/erpnext/issues/58279)) ([#58280](https://github.com/frappe/erpnext/issues/58280)) ([d047caf](d047caf4aa))
* filter available batch report by company (backport [#57995](https://github.com/frappe/erpnext/issues/57995)) ([#58076](https://github.com/frappe/erpnext/issues/58076)) ([8c8a4b6](8c8a4b6f20))
* fix conflicts ([f8e614f](f8e614f0c7))
* get items from sales order in sales invoice (backport [#58163](https://github.com/frappe/erpnext/issues/58163)) ([#58187](https://github.com/frappe/erpnext/issues/58187)) ([89d3701](89d3701e3b))
* hide rfq status in supplier portal ([#58368](https://github.com/frappe/erpnext/issues/58368)) ([2dbd224](2dbd224643))
* hide supplier name in rfq portal (backport [#58373](https://github.com/frappe/erpnext/issues/58373)) ([#58375](https://github.com/frappe/erpnext/issues/58375)) ([91fc999](91fc999575))
* ignore historical negative batch stock in outward validation (backport [#58148](https://github.com/frappe/erpnext/issues/58148)) ([#58150](https://github.com/frappe/erpnext/issues/58150)) ([9cc9aa0](9cc9aa0fa5))
* include time logs ending at midnight in timesheet billing summary (backport [#58355](https://github.com/frappe/erpnext/issues/58355)) ([#58356](https://github.com/frappe/erpnext/issues/58356)) ([3d4245b](3d4245b9b4))
* **italy:** handle none price_list_rate in e-invoice xml generation (backport [#58242](https://github.com/frappe/erpnext/issues/58242)) ([#58369](https://github.com/frappe/erpnext/issues/58369)) ([cb8ae93](cb8ae93fa3))
* **manufacturing:** derive material transfers from actual coverage ([#58114](https://github.com/frappe/erpnext/issues/58114)) ([a1ecea1](a1ecea1794))
* **manufacturing:** fall back to item group defaults for work order w… ([#58236](https://github.com/frappe/erpnext/issues/58236)) ([48bd313](48bd3139f3))
* mirror rounding adjustment on distributed_discount_amount (backport [#58047](https://github.com/frappe/erpnext/issues/58047)) ([#58054](https://github.com/frappe/erpnext/issues/58054)) ([b03e098](b03e098684))
* new docs should refetch incoming rates (backport [#58097](https://github.com/frappe/erpnext/issues/58097)) ([#58294](https://github.com/frappe/erpnext/issues/58294)) ([fd82c7d](fd82c7d691))
* **party_ledger_summary:** added missing filters for `cost_center` and `projects` ([#58411](https://github.com/frappe/erpnext/issues/58411)) ([d4815cb](d4815cb231))
* patch to delete the `crm_deal` custom fields ([ff1a191](ff1a1914a1))
* prevent duplicate supplier quotations from portal ([e1246ae](e1246ae95d))
* remove ignore_permissions from get_party_details signature ([#55491](https://github.com/frappe/erpnext/issues/55491)) ([4cd39aa](4cd39aa147))
* render missing terms before printing ([#58367](https://github.com/frappe/erpnext/issues/58367)) ([b33475e](b33475e7cf))
* respect zero currency precision ([#58395](https://github.com/frappe/erpnext/issues/58395)) ([6a84621](6a8462116b))
* **stock:** confirm before changing item qty from the batch selector (backport [#58123](https://github.com/frappe/erpnext/issues/58123)) ([#58124](https://github.com/frappe/erpnext/issues/58124)) ([954a5ec](954a5ec006))
* **stock:** fetch item stock UOM in stock reconciliation (backport [#58284](https://github.com/frappe/erpnext/issues/58284)) ([#58290](https://github.com/frappe/erpnext/issues/58290)) ([7883f59](7883f595d7))
* **stock:** honour pick serial / batch based on in the batch selector (backport [#58176](https://github.com/frappe/erpnext/issues/58176)) ([#58181](https://github.com/frappe/erpnext/issues/58181)) ([6d06b43](6d06b43434))
* update stock variance account logic which defaults to default expense (backport [#57656](https://github.com/frappe/erpnext/issues/57656)) ([#57675](https://github.com/frappe/erpnext/issues/57675)) ([c132b99](c132b99b4e))
* use user data fields hook (backport [#58274](https://github.com/frappe/erpnext/issues/58274)) ([#58282](https://github.com/frappe/erpnext/issues/58282)) ([74c3eea](74c3eeaa44))
* validation for task end date check ([8dc9919](8dc9919691))

### Features

* **accounts:** opt-in 'Consider Accounting Dimension' filter on General Ledger Report (backport [#58156](https://github.com/frappe/erpnext/issues/58156)) ([#58157](https://github.com/frappe/erpnext/issues/58157)) ([e704e58](e704e589ca))
* add status filter to Supplier Quotation Comparison report ([9e6a166](9e6a16658d))
* Belgian Charts of Accounts (commercial + non-profit, FR + NL) (backport [#54679](https://github.com/frappe/erpnext/issues/54679)) ([#58185](https://github.com/frappe/erpnext/issues/58185)) ([4c9a76e](4c9a76ef9f))
* sync serial no status from stock ledger in Stock Qty vs Serial No Count report (version-15-hotfix) ([#57865](https://github.com/frappe/erpnext/issues/57865)) ([faaaa07](faaaa0776d))
* taxable-base resolver hook for custom charge types ([#56175](https://github.com/frappe/erpnext/issues/56175)) ([8c9e941](8c9e941614))
* validate purchase receipt exchange rate parity on purchase invoice (backport [#58177](https://github.com/frappe/erpnext/issues/58177)) ([#58189](https://github.com/frappe/erpnext/issues/58189)) ([a5f4d3a](a5f4d3abeb))
2026-08-25 16:59:18 +00:00
Diptanil Saha
5d60bd9f54 Merge pull request #58396 from frappe/version-15-hotfix
chore: release v15
2026-08-25 22:27:36 +05:30
Diptanil Saha
d4815cb231 fix(party_ledger_summary): added missing filters for cost_center and projects (#58411) 2026-08-25 22:09:13 +05:30
Raffael Meyer
3ae3009129 fix!: tax net_amount and not_applicable (#54687) 2026-08-25 13:50:03 +02:00
Sudharsanan Ashok
07b6b3defd Merge pull request #58398 from frappe/mergify/bp/version-15-hotfix/pr-58395
fix: respect zero currency precision (backport #58395)
2026-08-25 16:45:17 +05:30
Pandiyan P
6a8462116b fix: respect zero currency precision (#58395)
(cherry picked from commit ce23fcc055)

# Conflicts:
#	erpnext/accounts/test/test_utils.py
2026-08-25 15:51:20 +05:30
Sudharsanan Ashok
1b5239c498 Merge pull request #58354 from frappe/mergify/bp/version-15-hotfix/pr-58179
fix(accounts): supplier group filter not applied on accounts payable … (backport #58179)
2026-08-25 13:04:42 +05:30
Sudharsanan Ashok
7fcbf085a5 Merge pull request #58389 from frappe/mergify/bp/version-15-hotfix/pr-58384
fix: prevent duplicate supplier quotations from portal (backport #58377) (backport #58384)
2026-08-25 12:04:54 +05:30
Sudharsanan11
f8e614f0c7 fix: fix conflicts 2026-08-25 11:47:06 +05:30
pandiyan
c861fbf438 test: verify duplicate supplier quotations are rejected
(cherry picked from commit efe5571ca7)
2026-08-25 05:43:13 +00:00
pandiyan
e1246ae95d fix: prevent duplicate supplier quotations from portal
(cherry picked from commit 39e15c7b2d)

# Conflicts:
#	erpnext/buying/doctype/request_for_quotation/request_for_quotation.py
2026-08-25 05:43:12 +00:00
mergify[bot]
91fc999575 fix: hide supplier name in rfq portal (backport #58373) (#58375)
Co-authored-by: Pandiyan P <pandiyanpalani37@gmail.com>
2026-08-24 17:40:38 +05:30
mergify[bot]
4b569c3ec3 Fix/return qty validation different uom (backport #58298) (#58363)
Co-authored-by: Vishnu Priya Baskaran <145791817+ervishnucs@users.noreply.github.com>
Co-authored-by: Afsal Syed <afsalsyed12@gmail.com>
2026-08-24 17:39:56 +05:30
mergify[bot]
cb8ae93fa3 fix(italy): handle none price_list_rate in e-invoice xml generation (backport #58242) (#58369)
Co-authored-by: Vishnu Priya Baskaran <145791817+ervishnucs@users.noreply.github.com>
2026-08-24 17:39:24 +05:30
Sudharsanan Ashok
91548461c0 Merge pull request #58371 from frappe/mergify/bp/version-15-hotfix/pr-58368
fix: hide rfq status in supplier portal (backport #58368)
2026-08-24 16:35:55 +05:30
Pandiyan P
2dbd224643 fix: hide rfq status in supplier portal (#58368)
(cherry picked from commit 75d6183bb6)
2026-08-24 10:59:54 +00:00
Pandiyan P
b33475e7cf fix: render missing terms before printing (#58367) 2026-08-24 16:28:17 +05:30
mergify[bot]
61238e7c4c fix: aggregate child warehouses in Stock Qty vs Serial No Count report (backport #58134) (#58365)
Co-authored-by: Mohd Haris <haris@frappe.io>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: Mihir Kandoi <kandoimihir@gmail.com>
2026-08-24 10:33:16 +00:00
mergify[bot]
3d4245b9b4 fix: include time logs ending at midnight in timesheet billing summary (backport #58355) (#58356)
Co-authored-by: Mihir Kandoi <kandoimihir@gmail.com>
2026-08-24 14:46:36 +05:30
ervishnucs
743f7d8713 fix(accounts): supplier group filter not applied on accounts payable report
(cherry picked from commit 513f19924d)
2026-08-24 07:12:19 +00:00
Vishnu Priya Baskaran
b578fb52d5 fix: allow custom remark on reversal journal entry (#58308)
fix: allow user remark on reversal journal entry
2026-08-19 22:18:13 +05:30
mergify[bot]
fd82c7d691 fix: new docs should refetch incoming rates (backport #58097) (#58294)
Co-authored-by: Mihir Kandoi <kandoimihir@gmail.com>
2026-08-19 11:58:32 +00:00
mergify[bot]
88a36a800a fix: block disabled/frozen party on Opportunity and Request for Quotation (backport #57983) (#58034)
* 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.

(cherry picked from commit 90937ce6d9)

# Conflicts:
#	erpnext/crm/doctype/opportunity/test_opportunity.py

* 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.

(cherry picked from commit 4bf65ffc1d)

# Conflicts:
#	erpnext/buying/doctype/request_for_quotation/request_for_quotation.py
#	erpnext/buying/doctype/request_for_quotation/test_request_for_quotation.py

* 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.

(cherry picked from commit 8c0a945417)

* 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).

(cherry picked from commit 6b35c51ff1)

* fix: resolve backport conflicts for disabled/frozen party validation

The automated backport left unresolved merge conflict markers committed
in request_for_quotation.py, test_request_for_quotation.py and
test_opportunity.py. Also fixes validate_party_frozen_disabled being
called with 3 args here, this branch's version only takes
(party_type, party_name), unlike develop's (company, party_type, party_name).

Dropped test_duplicate_supplier_rejected, test_rfq_blocked_for_supplier_with_prevent_rfqs
and test_rfq_status_lifecycle from the conflict resolution, they don't exist on
this branch and aren't part of this backport.

---------

Co-authored-by: Jatin3128 <jatinsarna8@gmail.com>
2026-08-19 16:58:21 +05:30
mergify[bot]
7883f595d7 fix(stock): fetch item stock UOM in stock reconciliation (backport #58284) (#58290)
Co-authored-by: Sudharsanan Ashok <135326972+Sudharsanan11@users.noreply.github.com>
Co-authored-by: Mihir Kandoi <kandoimihir@gmail.com>
2026-08-19 10:36:34 +00:00
mergify[bot]
c132b99b4e fix: update stock variance account logic which defaults to default expense (backport #57656) (#57675)
Co-authored-by: Afsal Syed <afsalsyed12@gmail.com>
Co-authored-by: Sudharsanan Ashok <135326972+Sudharsanan11@users.noreply.github.com>
2026-08-19 14:41:41 +05:30
mergify[bot]
74c3eeaa44 fix: use user data fields hook (backport #58274) (#58282)
Co-authored-by: Mihir Kandoi <kandoimihir@gmail.com>
2026-08-19 10:25:47 +05:30
mergify[bot]
1210c6187d fix: escape interpolated values in text positions across portal and desk templates (backport #58286) (#58287)
Co-authored-by: diptanilsaha <diptanil@frappe.io>
2026-08-19 02:44:35 +05:30
mergify[bot]
d047caf4aa fix: escape on status image for workstations in production status (backport #58279) (#58280)
Co-authored-by: Diptanil Saha <diptanil@frappe.io>
2026-08-18 20:27:31 +00:00
mergify[bot]
37f2770809 fix: escape interpolated values in portal, print and desk templates (backport #58273) (#58277)
Co-authored-by: diptanilsaha <diptanil@frappe.io>
2026-08-19 00:35:45 +05:30
mergify[bot]
b03e098684 fix: mirror rounding adjustment on distributed_discount_amount (backport #58047) (#58054)
Co-authored-by: Raffael Meyer <14891507+barredterra@users.noreply.github.com>
2026-08-18 12:07:43 +02:00
Frappe PR Bot
0526834071 chore(release): Bumped to Version 15.119.3
## [15.119.3](https://github.com/frappe/erpnext/compare/v15.119.2...v15.119.3) (2026-08-18)

### Bug Fixes

* get items from sales order in sales invoice (backport [#58163](https://github.com/frappe/erpnext/issues/58163)) (backport [#58187](https://github.com/frappe/erpnext/issues/58187)) ([#58259](https://github.com/frappe/erpnext/issues/58259)) ([88f32f1](88f32f1d1b))
2026-08-18 07:37:05 +00:00
mergify[bot]
88f32f1d1b fix: get items from sales order in sales invoice (backport #58163) (backport #58187) (#58259)
Co-authored-by: Mihir Kandoi <kandoimihir@gmail.com>
2026-08-18 07:35:00 +00:00
Lakshit Jain
41aba183de Merge pull request #58160 from frappe/mergify/bp/version-15-hotfix/pr-56175
feat: taxable-base resolver hook for custom charge types (backport #56175)
2026-08-18 11:58:24 +05:30
rohitwaghchaure
73b7ec32b6 fix: don't set work order status to In Process only due to skip material transfer (#58246) 2026-08-17 12:43:13 +00:00
Pandiyan P
48bd3139f3 fix(manufacturing): fall back to item group defaults for work order w… (#58236) 2026-08-17 15:26:05 +05:30
mergify[bot]
1464a34fc6 fix(bank_statement_import): add missing permission check on get_import_status (backport #58217) (#58218)
Co-authored-by: Diptanil Saha <diptanil@frappe.io>
2026-08-16 15:11:25 +00:00
mergify[bot]
0c625ff69b fix(crm)!: remove unused get_last_interaction endpoint (backport #58214) (#58215)
Co-authored-by: Diptanil Saha <diptanil@frappe.io>
2026-08-16 14:21:44 +00:00
Shllokkk
2aa1bf54f2 Merge pull request #58209 from frappe/mergify/bp/version-15-hotfix/pr-58208
feat: add status filter to Supplier Quotation Comparison report (backport #58208)
2026-08-16 19:48:40 +05:30
mergify[bot]
46d883d00d fix: correct Item Group doctype name in item tax template dashboard (backport #58192) (#58212) 2026-08-16 18:42:58 +05:30
mergify[bot]
32a5b23b3c fix: drop removed Restaurant doctype from sales tax template dashboard (backport #58191) (#58210) 2026-08-16 17:22:06 +05:30
Shllokkk
9e6a16658d feat: add status filter to Supplier Quotation Comparison report
(cherry picked from commit 2b84ed78e8)
2026-08-16 10:22:38 +00:00
mergify[bot]
c6211eb075 fix(email_digest): added permission check for get_msg_html (backport #58197) (#58199)
Co-authored-by: diptanilsaha <diptanil@frappe.io>
2026-08-15 16:47:02 +00:00
mergify[bot]
a5f4d3abeb feat: validate purchase receipt exchange rate parity on purchase invoice (backport #58177) (#58189)
* feat: validate purchase receipt exchange rate parity on purchase invoice (#58177)

(cherry picked from commit 70a8a2d0c5)

# Conflicts:
#	erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py

* chore: fix conflicts

Removed assertion for exchange rate discrepancy in purchase invoice test.

* test: fix backport of exchange rate difference test for non stock item

The conflict resolution left behind stale amount/discrepancy lookups
referencing a removed second item row (IndexError in CI and F841 ruff
failures). Align the test with the develop version: single non stock
item, PR at 80 / PI at 70, and assert no exchange gain/loss GL entry.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: rohitwaghchaure <rohitw1991@gmail.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-15 10:51:12 +00:00
mergify[bot]
89d3701e3b fix: get items from sales order in sales invoice (backport #58163) (#58187)
Co-authored-by: Mihir Kandoi <kandoimihir@gmail.com>
2026-08-15 08:02:23 +00:00
mergify[bot]
4c9a76ef9f feat: Belgian Charts of Accounts (commercial + non-profit, FR + NL) (backport #54679) (#58185)
Co-authored-by: Antoine Maas <antoine.maas@okte.io>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Diptanil Saha <diptanil@frappe.io>
2026-08-14 16:56:24 +00:00
mergify[bot]
6d06b43434 fix(stock): honour pick serial / batch based on in the batch selector (backport #58176) (#58181)
Co-authored-by: Sudharsanan Ashok <135326972+Sudharsanan11@users.noreply.github.com>
2026-08-14 13:57:27 +00:00
Khushi Rawat
78d780d49e Merge pull request #58175 from aerele/backport-58092-version-15-hotfix
fix(accounts): disallow reversing a reverse journal entry
2026-08-14 17:43:53 +05:30
pandiyan
15041a62dd fix(accounts): disallow reversing a reverse journal entry
check read permission on the source entry before the guard runs, so the reversal relationship is not disclosed to a user who cannot read it.
2026-08-14 17:06:23 +05:30
pandiyan
754e7052ca 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-14 16:56:06 +05:30
Nishka Gosalia
3b2bb23306 Merge pull request #58170 from frappe/mergify/bp/version-15-hotfix/pr-58167
fix: validation for task end date check (backport #58167)
2026-08-14 16:42:31 +05:30
mergify[bot]
e704e589ca feat(accounts): opt-in 'Consider Accounting Dimension' filter on General Ledger Report (backport #58156) (#58157)
Co-authored-by: Diptanil Saha <diptanil@frappe.io>
2026-08-14 16:27:37 +05:30
nishkagosalia
8dc9919691 fix: validation for task end date check
(cherry picked from commit 7c6da80f98)
2026-08-14 10:52:46 +00:00
vorasmit
e7e2358cb5 chore: resolve conflicts 2026-08-14 15:12:42 +05:30
Smit Vora
8c9e941614 feat: taxable-base resolver hook for custom charge types (#56175)
(cherry picked from commit 986cea2331)

# Conflicts:
#	erpnext/controllers/taxes_and_totals.py
#	erpnext/controllers/tests/test_taxes_and_totals.py
#	erpnext/public/js/controllers/taxes_and_totals.js
2026-08-14 08:19:25 +00:00
rohitwaghchaure
faaaa0776d feat: sync serial no status from stock ledger in Stock Qty vs Serial No Count report (version-15-hotfix) (#57865)
* 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

* fix: use posting datetime for last bundle move after version-15 field rename

* fix: order last bundle moves by bundle posting datetime
2026-08-14 11:51:18 +05:30
Frappe PR Bot
d707cb1e0e chore(release): Bumped to Version 15.119.2
## [15.119.2](https://github.com/frappe/erpnext/compare/v15.119.1...v15.119.2) (2026-08-14)

### Bug Fixes

* ignore historical negative batch stock in outward validation (backport [#58148](https://github.com/frappe/erpnext/issues/58148)) (backport [#58150](https://github.com/frappe/erpnext/issues/58150)) ([#58152](https://github.com/frappe/erpnext/issues/58152)) ([ac5b4d1](ac5b4d185b))
2026-08-14 06:20:14 +00:00
mergify[bot]
ac5b4d185b fix: ignore historical negative batch stock in outward validation (backport #58148) (backport #58150) (#58152)
fix: ignore historical negative batch stock in outward validation (backport #58148) (#58150)

fix: ignore historical negative batch stock in outward validation (#58148)

(cherry picked from commit 9239d1c2a3)


(cherry picked from commit 9cc9aa0fa5)

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
Co-authored-by: rohitwaghchaure <rohitw1991@gmail.com>
2026-08-14 11:48:34 +05:30
Khushi Rawat
15d430b959 Merge pull request #58093 from aerele/fix/budget-non-pnl-account-message
fix(accounts): attributeerror on budget against a non profit and loss account
2026-08-14 11:27:35 +05:30
mergify[bot]
9cc9aa0fa5 fix: ignore historical negative batch stock in outward validation (backport #58148) (#58150)
fix: ignore historical negative batch stock in outward validation (#58148)

(cherry picked from commit 9239d1c2a3)

Co-authored-by: rohitwaghchaure <rohitw1991@gmail.com>
2026-08-14 05:48:33 +00:00
Pandiyan P
81c53931b5 fix(buying): allow purchase returns against a closed purchase order (#58140) 2026-08-14 09:01:03 +05:30
mergify[bot]
167cc1e5b9 fix: asset scrap flow related changes (backport #55126) (#58144)
Co-authored-by: khushi8112 <khushirawat23@navgurukul.org>
2026-08-13 18:41:15 +00:00
Diptanil Saha
c6e6bdccae Merge pull request #58142 from frappe/mergify/bp/version-15-hotfix/pr-58141
fix(crm_settings): create `crm_deal` fields on enabling frappe crm data synchronization (backport #58141)
2026-08-13 23:28:36 +05:30
diptanilsaha
ff1a1914a1 fix: patch to delete the crm_deal custom fields
(cherry picked from commit 9613d72d81)
2026-08-13 17:39:51 +00:00
diptanilsaha
eb85ca68f6 fix(crm_settings): create custom fields for Frappe CRM on enabling synchronization
(cherry picked from commit be2dea0ba2)
2026-08-13 17:39:50 +00:00
mergify[bot]
954a5ec006 fix(stock): confirm before changing item qty from the batch selector (backport #58123) (#58124)
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.

(cherry picked from commit a2976dd29e)

Co-authored-by: Sudharsanan Ashok <135326972+Sudharsanan11@users.noreply.github.com>
2026-08-13 16:40:26 +05:30
Mihir Kandoi
a1ecea1794 fix(manufacturing): derive material transfers from actual coverage (#58114) 2026-08-13 09:39:21 +00:00
Diptanil Saha
a7e21e834d Merge pull request #58111 from frappe/mergify/bp/version-15-hotfix/pr-55491
fix: remove ignore_permissions from get_party_details signature (backport #55491)
2026-08-13 13:26:09 +05:30
diptanilsaha
23919967f6 chore: resolve conflicts 2026-08-13 13:01:53 +05:30
Shllokkk
4cd39aa147 fix: remove ignore_permissions from get_party_details signature (#55491)
(cherry picked from commit efb8336bf8)

# Conflicts:
#	erpnext/accounts/doctype/sales_invoice/sales_invoice.py
#	erpnext/accounts/party.py
2026-08-13 07:23:22 +00:00
Khushi Rawat
afa2437910 Merge pull request #57564 from khushi8112/refactor-depreciation-entry-v15
refactor: split make_depreciation_entry into public and internal helpers
2026-08-13 12:33:09 +05:30
Khushi Rawat
9638e81762 Merge pull request #58088 from frappe/mergify/bp/version-15-hotfix/pr-57820
fix(assets): split fifo/lifo rate across grouped stock item rows (backport #57820)
2026-08-13 12:28:26 +05:30
ervishnucs
1e23d48a5b test(assets): cover grouped stock item rows splitting FIFO rate
(cherry picked from commit 2cbc5b89d6)

# Conflicts:
#	erpnext/assets/doctype/asset_capitalization/test_asset_capitalization.py
2026-08-13 12:01:31 +05:30
khushi8112
6650ac8c36 refactor: split make_depreciation_entry into public and internal helpers 2026-08-13 11:39:33 +05:30
mergify[bot]
bfa3edbf95 Fix/item description in the item price list (backport #58084) (#58101)
Co-authored-by: Mohsin Akhtar <167299936+akhtarmohsin@users.noreply.github.com>
Co-authored-by: Mihir Kandoi <kandoimihir@gmail.com>
2026-08-13 04:42:02 +00:00
mergify[bot]
8c8a4b6f20 fix: filter available batch report by company (backport #57995) (#58076)
Co-authored-by: Krishna Shirsath <shirsathkrishna19@gmail.com>
2026-08-12 17:33:56 +05:30
pandiyan
2095411a28 fix: attributeerror on budget against a non profit and loss account 2026-08-12 16:12:55 +05:30
pandiyan
5700384989 test: budget against a balance sheet account 2026-08-12 16:12:55 +05:30
ervishnucs
c2c4e5ee8b fix(assets): split FIFO/LIFO rate across grouped stock item rows
(cherry picked from commit a05ec49062)
2026-08-12 09:04:48 +00:00
Frappe PR Bot
be176617cc chore(release): Bumped to Version 15.119.1
## [15.119.1](https://github.com/frappe/erpnext/compare/v15.119.0...v15.119.1) (2026-08-11)

### Bug Fixes

* **accounts receivable:** made territory field multi select (backport [#57322](https://github.com/frappe/erpnext/issues/57322)) ([#57808](https://github.com/frappe/erpnext/issues/57808)) ([69c00b3](69c00b3362))
* allow selecting a warehouse for new items in the update items dialog ([#57876](https://github.com/frappe/erpnext/issues/57876)) ([76f485b](76f485ba43))
* clear deferred revenue/expense fields on uncheck (backport [#57140](https://github.com/frappe/erpnext/issues/57140)) ([ce898a9](ce898a9695))
* **coa_importer:** added server-side validations for importing chart of accounts (backport [#58065](https://github.com/frappe/erpnext/issues/58065)) ([#58067](https://github.com/frappe/erpnext/issues/58067)) ([d0ef967](d0ef967890))
* **coa_importer:** allow importing COA through `import_coa` only for `Accounts Manager` (backport [#56132](https://github.com/frappe/erpnext/issues/56132)) ([#58064](https://github.com/frappe/erpnext/issues/58064)) ([00d8dc7](00d8dc73b9))
* convert hours to minutes in workstation complete_job ([5e753ec](5e753ec6e4))
* escape `customer_details` on lead creation from appointment (backport [#57947](https://github.com/frappe/erpnext/issues/57947)) ([#57948](https://github.com/frappe/erpnext/issues/57948)) ([2ca71f1](2ca71f16c4))
* field validation and perm checks on `get_stock_reservation_entries_for_voucher` (backport [#57968](https://github.com/frappe/erpnext/issues/57968)) ([#57986](https://github.com/frappe/erpnext/issues/57986)) ([a0d1561](a0d156120b))
* get_valuation_method takes no company argument on version-15 ([c45ea35](c45ea3545d))
* guard reconciliation table deletes when tables are missing ([140e06d](140e06dfa4))
* incorrect entry detection in Stock Ledger Invariant Check ([#57886](https://github.com/frappe/erpnext/issues/57886)) ([529ff25](529ff251fb))
* keep asset repair downtime in sync with entered dates ([0e9c08d](0e9c08d494))
* **manufacturing:** avoid child BOM cache lookups ([5c2123f](5c2123f6ed))
* **manufacturing:** correct nested BOM quantities ([a310346](a3103469e2))
* **manufacturing:** keep item code searchable when a barcode matches the same text ([0310db2](0310db22ec))
* optimize product bundle item search ([52a1b12](52a1b124b2))
* preserve custom title on new JV (backport [#57987](https://github.com/frappe/erpnext/issues/57987)) ([#57988](https://github.com/frappe/erpnext/issues/57988)) ([713af31](713af31eda))
* purchase return of batchwise valuation batch valued at original receipt rate instead of batch avg rate (version-15-hotfix) ([#57837](https://github.com/frappe/erpnext/issues/57837)) ([e2ded11](e2ded11e09))
* re-check future sle before queuing repost on submit ([#57664](https://github.com/frappe/erpnext/issues/57664)) ([#57960](https://github.com/frappe/erpnext/issues/57960)) ([d510978](d510978a44))
* reflect in-invoice receivable settlements in Sales Register ledger view ([91afc04](91afc04d9f))
* repost read stale sibling SLE rate for moving average returns ([5738cfc](5738cfce79))
* require material transfer before job card time logs ([2e5ae18](2e5ae188d6))
* resolve version-15 backport conflicts ([b25a2f2](b25a2f2cdf))
* **selling:** bill re-delivered sales order quantities ([47c6274](47c6274b13))
* **selling:** reset stale item details on item change (backport [#58051](https://github.com/frappe/erpnext/issues/58051)) ([#58052](https://github.com/frappe/erpnext/issues/58052)) ([01372cf](01372cf295))
* set `restrict_globals=True` in `frappe.render_template` (backport [#57899](https://github.com/frappe/erpnext/issues/57899)) ([#57901](https://github.com/frappe/erpnext/issues/57901)) ([af7953a](af7953a933))
* **setup:** fetch driver address by supplier link ([2a4a9ff](2a4a9fff3d))
* skip incoming rate calc when serial no qty is zero (backport [#57427](https://github.com/frappe/erpnext/issues/57427)) ([#57956](https://github.com/frappe/erpnext/issues/57956)) ([f9a09f0](f9a09f0ac4))
* **stock:** grant account access in blanket order role test ([5e78603](5e7860362e))
* **stock:** handle multi-item opening balance in Stock Ledger report (backport [#57591](https://github.com/frappe/erpnext/issues/57591)) ([#57795](https://github.com/frappe/erpnext/issues/57795)) ([ebdc0cd](ebdc0cdf7f))
* **stock:** scope over deliver/receive role check to delivery and receipt overflow ([328c72d](328c72da18))
* **stock:** validate new warehouse inventory account after naming ([5e3d094](5e3d0947c8))
* **stock:** validate over delivery/receipt allowance in stock settings ([7be8a99](7be8a99a23))
* **stock:** validate warehouse accounts when used ([d620720](d620720445))
* **subscription:** don't reactivate a cancelled subscription (backport [#57774](https://github.com/frappe/erpnext/issues/57774)) ([#57780](https://github.com/frappe/erpnext/issues/57780)) ([edc8daa](edc8daae21)), closes [#57761](https://github.com/frappe/erpnext/issues/57761) [#57761](https://github.com/frappe/erpnext/issues/57761)
* sync open reference forms after Quality Inspection updates them ([c1d198d](c1d198d205))
* tolerate floating-point drift in sales team allocated percentage ([262fbc5](262fbc52d8))
* use stock settings for warehouse defaults ([d4ed207](d4ed2074d5))
* validate webform for project ([680ce70](680ce70c35))
* zero-rate repost fallback could still read sibling SLE ([8131af9](8131af9405))
2026-08-11 23:19:46 +00:00
Diptanil Saha
942a1ddb2c Merge pull request #58025 from frappe/version-15-hotfix
chore: release v15
2026-08-12 04:47:53 +05:30
Diptanil Saha
d0ef967890 fix(coa_importer): added server-side validations for importing chart of accounts (backport #58065) (#58067) 2026-08-11 22:54:34 +00:00
Diptanil Saha
00d8dc73b9 fix(coa_importer): allow importing COA through import_coa only for Accounts Manager (backport #56132) (#58064)
Co-authored-by: Pratheep S <pratheeps2024@gmail.com>
2026-08-11 21:16:40 +00:00
mergify[bot]
01372cf295 fix(selling): reset stale item details on item change (backport #58051) (#58052) 2026-08-11 15:54:04 +00:00
Mihir Kandoi
9c9bc8e9bf Merge pull request #58039 from mihir-kandoi/backport-58036-version-15-hotfix
fix(stock): validate warehouse accounts when used (backport #58036)
2026-08-11 19:15:29 +05:30
Mihir Kandoi
5a61ea6496 test(stock): isolate warehouse account fixtures from class-level state
FrappeTestCase on this branch rolls back per class, not per test, so
sibling tests leak state. test_new_warehouse_can_inherit_inventory_account
left an explicit account on the root group, which made later ambiguous
fixtures resolve through the root: the insert validation stopped raising
and the unresolved warehouse stayed in the map.

The fixture helper now clears group warehouse accounts so every call
re-establishes ambiguity. The fallback test also clears the account of
the warehouse it picks, since a leftover explicit account skips the
single-account fallback it asserts.
2026-08-11 18:58:49 +05:30
Mihir Kandoi
da2c422bf6 test(stock): cover named validation error and same-transaction parent inheritance 2026-08-11 18:31:25 +05:30
Mihir Kandoi
5e3d0947c8 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:31:25 +05:30
Mihir Kandoi
d620720445 fix(stock): validate warehouse accounts when used 2026-08-11 18:04:30 +05:30
Mihir Kandoi
f5e411669a Merge pull request #58022 from frappe/mergify/bp/version-15-hotfix/pr-58020
fix(setup): fetch driver address by supplier link (backport #58020)
2026-08-11 15:31:09 +05:30
Mihir Kandoi
2a4a9fff3d fix(setup): fetch driver address by supplier link
(cherry picked from commit 3ffb888d26)
2026-08-11 09:47:54 +00:00
Mihir Kandoi
5c3063fa43 Merge pull request #58011 from mihir-kandoi/backport-58003-version-15-hotfix
fix(selling): bill re-delivered sales order quantities (backport #58003)
2026-08-11 14:10:29 +05:30
Mihir Kandoi
39e4641a29 Merge pull request #58015 from mihir-kandoi/require-transfer-before-job-card-start-v15
fix: require material transfer before job card time logs (v15)
2026-08-11 14:04:17 +05:30
Mihir Kandoi
ac4e9c34cf chore(selling): annotate make_sales_invoice arguments 2026-08-11 13:49:48 +05:30
Mihir Kandoi
b70fa4fdd1 test: job card time log blocked until material transfer 2026-08-11 13:41:59 +05:30
Mihir Kandoi
2e5ae188d6 fix: require material transfer before job card time logs
v15 adaptation of the develop fix: the timer flow here runs through
add_time_log via make_time_log, so gate that instead of the
start_timer/complete_job_card methods that only exist on develop, and
hide Start Job while transfer is pending. Corrective job cards and
job cards without items (transfer against Work Order) stay exempt,
matching validate_transfer_qty on submit.
2026-08-11 13:41:57 +05:30
Mihir Kandoi
a99b10d213 Merge pull request #58008 from frappe/codex/backport-57963-version-15
fix(manufacturing): correct nested BOM Explorer quantities
2026-08-11 13:34:29 +05:30
Mihir Kandoi
220b25db09 test(selling): cover invoicing after returns and re-deliveries 2026-08-11 13:26:00 +05:30
Mihir Kandoi
47c6274b13 fix(selling): bill re-delivered sales order quantities 2026-08-11 13:25:59 +05:30
Mihir Kandoi
5c2123f6ed fix(manufacturing): avoid child BOM cache lookups 2026-08-11 13:14:49 +05:30
Mihir Kandoi
bb72ae6a3c Merge pull request #58001 from frappe/mergify/bp/version-15-hotfix/pr-57997
fix: keep item code searchable when a barcode matches the same text (backport #57997)
2026-08-11 13:08:48 +05:30
Mihir Kandoi
a3103469e2 fix(manufacturing): correct nested BOM quantities 2026-08-11 13:01:41 +05:30
Mihir Kandoi
43b874f0d4 Merge pull request #57998 from frappe/mergify/bp/version-15-hotfix/pr-57972
refactor: drop redundant time_in_mins assignment in workstation complete_job (backport #57972)
2026-08-11 12:28:42 +05:30
Kaushal Shriwas
a9743ae5da chore: resolve backport conflict in bom.py 2026-08-11 12:25:29 +05:30
Kaushal Shriwas
760b365225 test(manufacturing): cover BOM item search when item code collides with a barcode
(cherry picked from commit 23024d1ea9)
2026-08-11 06:42:55 +00:00
Kaushal Shriwas
0310db22ec fix(manufacturing): keep item code searchable when a barcode matches the same text
(cherry picked from commit bf5d506637)

# Conflicts:
#	erpnext/manufacturing/doctype/bom/mapper.py
2026-08-11 06:42:55 +00:00
Mihir Kandoi
496883f4e1 refactor: drop redundant time_in_mins assignment in complete_job
(cherry picked from commit 3cffeb68e3)
2026-08-11 06:39:14 +00:00
pandiyan
5e753ec6e4 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.

(cherry picked from commit 422a9161dd)
2026-08-11 06:39:14 +00:00
mergify[bot]
27af9baaa5 refactor(queries): using frappe.get_query in get_filtered_child_rows (backport #57991) (#57992)
Co-authored-by: Diptanil Saha <diptanil@frappe.io>
2026-08-10 19:51:55 +00:00
mergify[bot]
a0d156120b fix: field validation and perm checks on get_stock_reservation_entries_for_voucher (backport #57968) (#57986)
Co-authored-by: Diptanil Saha <diptanil@frappe.io>
2026-08-10 22:04:42 +05:30
mergify[bot]
713af31eda fix: preserve custom title on new JV (backport #57987) (#57988)
Co-authored-by: rehanrehman389 <rehanrehman389@gmail.com>
Co-authored-by: Diptanil Saha <diptanil@frappe.io>
2026-08-10 16:27:03 +00:00
ruthra kumar
df8edcdc91 Merge pull request #57830 from aerele/backport-57140-v15
fix: clear deferred revenue/expense fields on uncheck (backport #57140)
2026-08-10 15:04:11 +05:30
Pandiyan P
d510978a44 fix: re-check future sle before queuing repost on submit (#57664) (#57960)
* test: cover both repost branches and the no-repost case

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

---------


(cherry picked from commit 399ff463cc)

Co-authored-by: nareshkannasln <nareshkannashanmugam@gmail.com>
2026-08-10 14:03:41 +05:30
mergify[bot]
f9a09f0ac4 fix: skip incoming rate calc when serial no qty is zero (backport #57427) (#57956)
fix: skip incoming rate calc when serial no qty is zero (#57427)

(cherry picked from commit a25decfa50)

Co-authored-by: Shllokkk <140623894+Shllokkk@users.noreply.github.com>
2026-08-10 06:48:58 +00:00
Khushi Rawat
a2b2f5173e Merge pull request #57823 from Shllokkk/asset-repair-downtime-recalc-v15
fix: keep asset repair downtime in sync with entered dates
2026-08-10 12:05:01 +05:30
mergify[bot]
2ca71f16c4 fix: escape customer_details on lead creation from appointment (backport #57947) (#57948)
Co-authored-by: Diptanil Saha <diptanil@frappe.io>
2026-08-09 19:30:11 +00:00
Shllokkk
ae18d13e6e Merge pull request #57928 from Shllokkk/sales-register-ledger-pos-paid-v15
fix: reflect in-invoice receivable credits in Sales Register ledger view
2026-08-09 23:39:00 +05:30
Shllokkk
7edb95628c test: cover POS-paid invoice in Sales Register ledger view 2026-08-09 20:22:31 +05:30
Shllokkk
91afc04d9f fix: reflect in-invoice receivable settlements in Sales Register ledger view 2026-08-09 20:22:31 +05:30
Mihir Kandoi
3c5b2ededf Merge pull request #57920 from frappe/mergify/bp/version-15-hotfix/pr-57918
fix: sync open reference forms after Quality Inspection submit (backport #57918)
2026-08-09 16:38:01 +05:30
Mihir Kandoi
94d1dfdcb4 chore: resolve conflict 2026-08-09 16:18:49 +05:30
Mihir Kandoi
2270b22400 test: doc_update published for reference on Quality Inspection submit
(cherry picked from commit e8a6884d5e)

# Conflicts:
#	erpnext/stock/doctype/quality_inspection/test_quality_inspection.py
2026-08-09 10:39:05 +00:00
Mihir Kandoi
c1d198d205 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.

(cherry picked from commit 647452c95b)
2026-08-09 10:39:05 +00:00
Mihir Kandoi
db4f6db753 Merge pull request #57909 from frappe/mergify/bp/version-15-hotfix/pr-57876
fix: allow selecting a warehouse for new items in the update items dialog (backport #57876)
2026-08-09 13:17:57 +05:30
Mihir Kandoi
ee27df7d2b Merge pull request #57912 from frappe/mergify/bp/version-15-hotfix/pr-57911
fix: tolerate floating-point drift in sales team allocated percentage  (backport #57911)
2026-08-09 13:07:26 +05:30
Mihir Kandoi
d4ed2074d5 fix: use stock settings for warehouse defaults 2026-08-09 13:01:01 +05:30
Mihir Kandoi
206d291817 chore: resolve conflict 2026-08-09 12:50:38 +05:30
Mihir Kandoi
c23aa72dff chore: resolve conflict 2026-08-09 12:41:55 +05:30
pandiyan
1a89609044 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.

(cherry picked from commit 4afba94d1c)

# Conflicts:
#	erpnext/selling/doctype/sales_order/test_sales_order.py
2026-08-09 06:59:23 +00:00
pandiyan
262fbc52d8 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.

(cherry picked from commit f7b2775829)
2026-08-09 06:59:22 +00:00
mergify[bot]
7d9abee6b4 refactor(accounts)!: rework Purchase Invoice hold actions and enforce them on Journal Entry (backport #57825) (#57867)
Co-authored-by: diptanilsaha <diptanil@frappe.io>
2026-08-09 06:50:44 +00:00
Pandiyan P
76f485ba43 fix: allow selecting a warehouse for new items in the update items dialog (#57876)
(cherry picked from commit 55fe269046)

# Conflicts:
#	erpnext/accounts/services/child_item_update.py
#	erpnext/public/js/utils.js
#	erpnext/selling/doctype/sales_order/test_sales_order.py
2026-08-09 06:01:36 +00:00
Mihir Kandoi
8fc5cb2444 Merge pull request #57907 from frappe/mergify/bp/version-15-hotfix/pr-57832
fix: validate webform for project (backport #57832)
2026-08-09 09:59:47 +05:30
nishkagosalia
680ce70c35 fix: validate webform for project
(cherry picked from commit 126966d1db)
2026-08-09 04:12:10 +00:00
mergify[bot]
af7953a933 fix: set restrict_globals=True in frappe.render_template (backport #57899) (#57901)
Co-authored-by: Diptanil Saha <diptanil@frappe.io>
2026-08-09 00:04:14 +05:30
Mihir Kandoi
de9d306bfd Merge pull request #57891 from mihir-kandoi/backport-57887-v15
fix: repost read stale sibling SLE rate for moving average returns (backport #57887)
2026-08-08 12:02:32 +05:30
Mihir Kandoi
e63a81b269 Merge pull request #57888 from frappe/mergify/bp/version-15-hotfix/pr-57886
fix: incorrect entry detection in Stock Ledger Invariant Check (backport #57886)
2026-08-08 11:43:21 +05:30
Mihir Kandoi
c45ea3545d fix: get_valuation_method takes no company argument on version-15 2026-08-08 11:24:44 +05:30
Mihir Kandoi
8131af9405 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:12:41 +05:30
Mihir Kandoi
9c8d5ac8a5 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 11:12:41 +05:30
Mihir Kandoi
5738cfce79 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 11:12:41 +05:30
Mihir Kandoi
529ff251fb fix: incorrect entry detection in Stock Ledger Invariant Check (#57886)
(cherry picked from commit b3f97cd389)
2026-08-08 05:31:48 +00:00
Shllokkk
ec7d7cce5c Merge pull request #57881 from frappe/mergify/bp/version-15-hotfix/pr-57880
fix: guard reconciliation table deletes when tables are missing (backport #57880)
2026-08-07 22:00:33 +05:30
Shllokkk
140e06dfa4 fix: guard reconciliation table deletes when tables are missing
(cherry picked from commit 8a2b2a2b68)
2026-08-07 14:34:58 +00:00
Mihir Kandoi
522d7bb1a9 Merge pull request #57869 from frappe/mergify/bp/version-15-hotfix/pr-57866
fix: optimize product bundle item search (backport #57866)
2026-08-07 16:05:07 +05:30
Krishna Shirsath
52a1b124b2 fix: optimize product bundle item search
(cherry picked from commit b3867f1428)
2026-08-07 10:33:15 +00:00
rohitwaghchaure
e2ded11e09 fix: purchase return of batchwise valuation batch valued at original receipt rate instead of batch avg rate (version-15-hotfix) (#57837)
* 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:20:34 +05:30
pandiyan
ce898a9695 fix: clear deferred revenue/expense fields on uncheck (backport #57140) 2026-08-06 11:25:35 +05:30
Shllokkk
242c950d1b test: assert asset repair downtime recalculates on date change 2026-08-06 00:33:58 +05:30
Shllokkk
0e9c08d494 fix: keep asset repair downtime in sync with entered dates 2026-08-06 00:33:58 +05:30
Mihir Kandoi
1bfe2e25ef Merge pull request #57727 from frappe/mergify/bp/version-15-hotfix/pr-57725
fix(stock): scope over deliver/receive role check to delivery and receipt overflow (backport #57725)
2026-08-05 16:05:25 +05:30
Sudharsanan11
5e7860362e fix(stock): grant account access in blanket order role test 2026-08-05 15:16:27 +05:30
Mihir Kandoi
b25a2f2cdf fix: resolve version-15 backport conflicts
Keep validate_warehouses() and add validate_over_delivery_receipt_allowance();
validate_serial_and_batch_no_settings() does not exist on this branch.

Keep this branch's field labels and add only the non_negative flag the
backported commit introduced.

Drop test_over_order_allowance_against_material_request and
test_blanket_order_over_order_aggregated_across_rows: both are develop-only
context the cherry-pick swallowed into the conflicts, and Buying Settings has
no over_order_allowance field here.

Use frappe.tests.utils.change_settings instead of ERPNextTestSuite, which this
branch does not have.

Revert the valuation_method literal to the three options this branch offers -
Standard Cost rode along from a regenerated develop type block.
2026-08-05 15:16:27 +05:30
Afsal Syed
21c3e07f48 test(stock): prevent settings leakage in purchase order tests
(cherry picked from commit 99630f40eb)

# Conflicts:
#	erpnext/buying/doctype/purchase_order/test_purchase_order.py
2026-08-05 15:16:27 +05:30
Afsal Syed
f5ab55c38d test(stock): add test cases verifying stock over delivery role does not bypass order allowance
(cherry picked from commit 0b271e24b6)

# Conflicts:
#	erpnext/buying/doctype/purchase_order/test_purchase_order.py
#	erpnext/manufacturing/doctype/blanket_order/test_blanket_order.py
2026-08-05 15:16:27 +05:30
Afsal Syed
328c72da18 fix(stock): scope over deliver/receive role check to delivery and receipt overflow
(cherry picked from commit 248873034d)

# Conflicts:
#	erpnext/controllers/status_updater.py
2026-08-05 15:16:27 +05:30
Afsal Syed
7be8a99a23 fix(stock): validate over delivery/receipt allowance in stock settings
(cherry picked from commit 446ec6030a)

# Conflicts:
#	erpnext/stock/doctype/stock_settings/stock_settings.json
#	erpnext/stock/doctype/stock_settings/stock_settings.py
2026-08-05 15:16:27 +05:30
mergify[bot]
ebdc0cdf7f fix(stock): handle multi-item opening balance in Stock Ledger report (backport #57591) (#57795)
* 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>
(cherry picked from commit 0dbe410414)

# Conflicts:
#	erpnext/stock/report/stock_ledger/stock_ledger.py
#	erpnext/stock/report/stock_ledger/test_stock_ledger_report.py

* fix(stock): resolve stock ledger backport conflicts

---------

Co-authored-by: Sudharsanan Ashok <135326972+Sudharsanan11@users.noreply.github.com>
Co-authored-by: Sudharsanan11 <sudharsananashok1975@gmail.com>
2026-08-05 13:15:59 +05:30
mergify[bot]
69c00b3362 fix(accounts receivable): made territory field multi select (backport #57322) (#57808)
fix(accounts receivable): made territory field multi select (#57322)

(cherry picked from commit 1029cd988a)

Co-authored-by: Jatin3128 <140256508+Jatin3128@users.noreply.github.com>
2026-08-05 07:35:28 +00:00
Jatin3128
edc8daae21 fix(subscription): don't reactivate a cancelled subscription (backport #57774) (#57780)
* fix(subscription): don't reactivate a cancelled subscription

Backport of #57774 to version-15-hotfix.

set_subscription_status() unconditionally set status to Active once
there was no outstanding invoice, with no check for whether the
subscription had been intentionally cancelled. 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 reprocess.

version-15-hotfix does not yet have the Payment Entry -> invoice ->
refresh_subscription_status() hook chain that #57761 reports (that
was added later), and the scheduler already excludes Cancelled
subscriptions, so the exact automatic repro in the issue does not
apply here. The underlying status logic is defective the same way
though, and reachable directly (e.g. any caller invoking the
whitelisted process()/set_subscription_status() on a cancelled
subscription), so fixing it here too rather than leaving the same
class of bug in place.

Related to #57761

* fix(test): avoid tripping the unrelated period-end cancel clause

The test backdated start_date to 2018-01-01, so by the time process()
ran, current_invoice_end was long past. That made the *other* half of
the cancel_at_period_end OR-condition (period end reached) true on
its own, so process() tried to cancel an already-cancelled
subscription and hit cancel_subscription()'s "already cancelled"
guard - unrelated to the empty end_date bug being tested.

Use nowdate() as start_date so current_invoice_end sits safely in the
future, isolating the assertion to the empty end_date guard. Also
drop the fragile intermediate "Unpaid" status assertion, which
wasn't part of what this test verifies.

* fix(subscription): don't let period rollover defeat cancel_at_period_end

process() can advance current_invoice_end to the next period (via
update_subscription_period(), when generating the current period's
invoice) before the cancel_at_period_end check further down runs. For
a subscription with no end_date, that check now compared posting_date
against the already-rolled-forward current_invoice_end, which is
always in the future, so cancel_at_period_end was silently never
honored.

Snapshot current_invoice_end before any rollover and use that in the
check instead, so it still targets the period that just ended.

Fixes the P1 flagged by Greptile review on this PR.

---------

Co-authored-by: test <test@test.com>
2026-08-05 12:26:01 +05:30
Frappe PR Bot
866688931b chore(release): Bumped to Version 15.119.0
# [15.119.0](https://github.com/frappe/erpnext/compare/v15.118.3...v15.119.0) (2026-08-04)

### Bug Fixes

* **accounts:** fetch deferred invoice docs on non-empty `sales_docs` or `purchase_docs` in repost accounting ledger (backport [#57753](https://github.com/frappe/erpnext/issues/57753)) ([#57756](https://github.com/frappe/erpnext/issues/57756)) ([ee4e296](ee4e296ce6))
* **accounts:** skip party dashboard without invoice permission ([9d417da](9d417da3d8))
* **accounts:** update AU standard chart of accounts (backport [#57145](https://github.com/frappe/erpnext/issues/57145)) ([#57607](https://github.com/frappe/erpnext/issues/57607)) ([15c3817](15c381701d))
* **assets:** add permission checks on whitelisted methods on `asset_capitalization` ([338fff2](338fff20db))
* do not fetch a random inventory account when multiple inventory accounts exist (backport [#57626](https://github.com/frappe/erpnext/issues/57626)) ([#57631](https://github.com/frappe/erpnext/issues/57631)) ([972a990](972a990b01))
* escape data in multiple templates (backport [#57742](https://github.com/frappe/erpnext/issues/57742)) ([#57769](https://github.com/frappe/erpnext/issues/57769)) ([928f984](928f984198))
* filter Accounts Receivable by invoice sales partner (backport [#57628](https://github.com/frappe/erpnext/issues/57628)) ([#57646](https://github.com/frappe/erpnext/issues/57646)) ([ebf5a46](ebf5a462b3))
* guard against None row in get_stock_balance_for (backport [#57567](https://github.com/frappe/erpnext/issues/57567)) ([72f293f](72f293f131))
* Ignore permission while deleting user permission ([faa7c46](faa7c466b1))
* incorrect batch-wise valuation rate for entries with same posting datetime ([#57794](https://github.com/frappe/erpnext/issues/57794)) ([431dc2e](431dc2e5f1))
* **item_variant:** added permission checks on `enqueue_multiple_variant_creation` ([9cd5997](9cd5997500))
* let Purchase Receipt cancel defer to Frappe's linked-document check (backport [#57592](https://github.com/frappe/erpnext/issues/57592)) ([#57602](https://github.com/frappe/erpnext/issues/57602)) ([7cecff9](7cecff9fa4))
* **opportunity:** add validation for positive item quantities ([f47346a](f47346aa90))
* **payment reconciliation:** correct supplier gain/loss posting ([78cd25d](78cd25de04))
* **payment_request:** added permission checks on `resend_payment_email` ([c38c9d5](c38c9d5d9b))
* **plant_floor:** add missing perm check on `get_stock_summary` (backport [#57667](https://github.com/frappe/erpnext/issues/57667)) ([#57669](https://github.com/frappe/erpnext/issues/57669)) ([42d5378](42d53783bb))
* preserve UOM conversion factor precision in transactions ([4373e29](4373e295de))
* prevent duplicate shipping charges without cost center ([a6dff3f](a6dff3fc47))
* **projects:** add project filter ([54390bd](54390bdeb9))
* **projects:** include on hold status in project filters and reports ([478426b](478426b436))
* **purchase:** reject purchase returns where every item has zero quantity ([8676add](8676add875))
* **quotation:** carry forward communications from opportunity at after_insert (backport [#57639](https://github.com/frappe/erpnext/issues/57639)) ([#57642](https://github.com/frappe/erpnext/issues/57642)) ([cf42c52](cf42c52530))
* resolve backport conflicts for version-15 ([1602639](1602639a80))
* resolve version 15 backport conflict ([00df865](00df8652e3))
* resolve version-15 backport conflict ([70da05e](70da05edb7))
* respect quantity precision in material transfer validation ([a5ed3a5](a5ed3a5945))
* **sales:** reject sales returns where every item has zero quantity ([48beb2e](48beb2ee23))
* seed standard Item Groups under the existing tree root ([8483350](848335086c)), closes [#57581](https://github.com/frappe/erpnext/issues/57581)
* set transaction currency on payment entry gl entries ([#57613](https://github.com/frappe/erpnext/issues/57613)) ([35f523e](35f523e2dd))
* source manually created asset value from valuation rate ([455d6d4](455d6d4ac1))
* **stock:** pick list serial batch posting date ([#57015](https://github.com/frappe/erpnext/issues/57015)) ([a51750d](a51750db56)), closes [#56951](https://github.com/frappe/erpnext/issues/56951)
* **stock:** validate only the variant attributes that changed ([2993747](2993747636))
* **stock:** value batched packed-item returns from the original bundle  (backport [#57327](https://github.com/frappe/erpnext/issues/57327)) ([#57510](https://github.com/frappe/erpnext/issues/57510)) ([94d63eb](94d63ebb49))
* use payment entry posting date for received amount exchange rate (backport [#57660](https://github.com/frappe/erpnext/issues/57660)) ([#57662](https://github.com/frappe/erpnext/issues/57662)) ([b826b7c](b826b7c3e6))
* validate account frozen date ([310b9d4](310b9d4e65))

### Features

* auto-fill subscription accounting dimensions from plan with item fallback (backport [#57615](https://github.com/frappe/erpnext/issues/57615)) ([#57621](https://github.com/frappe/erpnext/issues/57621)) ([bb36a4f](bb36a4fd08))
* make Shipping Rule Cost Center optional with company default fallback (backport [#57355](https://github.com/frappe/erpnext/issues/57355)) ([#57402](https://github.com/frappe/erpnext/issues/57402)) ([b2918b8](b2918b8bb3))
* status based bar colors in Work Order gantt view (backport [#57634](https://github.com/frappe/erpnext/issues/57634)) ([#57635](https://github.com/frappe/erpnext/issues/57635)) ([68c24f3](68c24f3767))
2026-08-04 20:31:08 +00:00
Diptanil Saha
f0d1887e6e Merge pull request #57782 from frappe/version-15-hotfix
chore: release v15
2026-08-05 01:59:03 +05:30
Shllokkk
e3af2f9302 Merge pull request #57800 from Shllokkk/savc-child-account-override-test
test: child warehouse account override in stock vs account value comparison
2026-08-05 01:35:33 +05:30
mergify[bot]
15c381701d fix(accounts): update AU standard chart of accounts (backport #57145) (#57607)
fix(accounts): update AU standard chart of accounts (#57145)


(cherry picked from commit fee3a6e0fd)

Co-authored-by: Diptanil Saha <diptanil@frappe.io>
Co-authored-by: Jebajebas <jeba.j@arus.co.in>
2026-08-04 19:22:31 +00:00
Vishnu Priya Baskaran
35f523e2dd fix: set transaction currency on payment entry gl entries (#57613) 2026-08-05 00:39:37 +05:30
Diptanil Saha
a19fd5d6b5 Merge pull request #57799 from frappe/mergify/bp/version-15-hotfix/pr-57798
fix(payment reconciliation): correct supplier gain/loss posting (backport #57734)
2026-08-05 00:34:25 +05:30
Shllokkk
25bd2bd4e7 test: child warehouse account override excluded in stock vs account value comparison 2026-08-05 00:31:29 +05:30
Sudharsanan11
387f2b5d01 test(payment reconciliation): cover supplier exchange gain posting
(cherry picked from commit 61154e22ed)
2026-08-04 18:44:12 +00:00
diptanilsaha
78cd25de04 fix(payment reconciliation): correct supplier gain/loss posting
(cherry picked from commit dc907add40)
2026-08-04 18:44:11 +00:00
rohitwaghchaure
431dc2e5f1 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.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* 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>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-04 22:53:56 +05:30
Mihir Kandoi
3aed38423e Merge pull request #57787 from frappe/mergify/bp/version-15-hotfix/pr-57757
fix(opportunity): add validation for positive item quantities (backport #57757)
2026-08-04 17:26:58 +05:30
Mihir Kandoi
33446f4f4a Merge pull request #57784 from frappe/mergify/bp/version-15-hotfix/pr-57772
fix(accounts): skip party dashboard without invoice permission (backport #57772)
2026-08-04 16:59:39 +05:30
R-Jayaraman
7ef039f6ed chore: use flt() in qty check
(cherry picked from commit 69de8f2d62)
2026-08-04 11:23:36 +00:00
R-Jayaraman
f47346aa90 fix(opportunity): add validation for positive item quantities
(cherry picked from commit c47cc37441)
2026-08-04 11:23:35 +00:00
Sudharsanan11
9d417da3d8 fix(accounts): skip party dashboard without invoice permission
(cherry picked from commit ed78dd37be)
2026-08-04 11:04:04 +00:00
mergify[bot]
928f984198 fix: escape data in multiple templates (backport #57742) (#57769)
Co-authored-by: diptanilsaha <diptanil@frappe.io>
2026-08-04 09:56:46 +00:00
Deepesh Garg
78a43833a0 Merge pull request #57759 from frappe/mergify/bp/version-15-hotfix/pr-57296
fix: Ignore permission while deleting user permission (#57296)
2026-08-03 19:06:58 +05:30
Deepesh Garg
faa7c466b1 fix: Ignore permission while deleting user permission
(cherry picked from commit 3b10ff7df7)
2026-08-03 13:02:49 +00:00
mergify[bot]
ee4e296ce6 fix(accounts): fetch deferred invoice docs on non-empty sales_docs or purchase_docs in repost accounting ledger (backport #57753) (#57756)
Co-authored-by: Diptanil Saha <diptanil@frappe.io>
2026-08-03 12:33:56 +00:00
Mihir Kandoi
0b08129b40 Merge pull request #57749 from frappe/mergify/bp/version-15-hotfix/pr-57747
fix: disabled item attribute blocks unrelated edits to existing variants (backport #57747)
2026-08-03 17:03:26 +05:30
Mihir Kandoi
c488de8f12 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:45 +05:30
Mihir Kandoi
005b626482 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.

(cherry picked from commit 8d5326196e)
2026-08-03 10:47:25 +00:00
Mihir Kandoi
2993747636 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.

(cherry picked from commit 25cd793617)
2026-08-03 10:47:24 +00:00
Mihir Kandoi
a9a3c20f3f Merge pull request #57729 from frappe/mergify/bp/version-15-hotfix/pr-57647
fix(sales): reject sales returns where every item has zero quantity (backport #57647)
2026-08-03 13:51:58 +05:30
Mihir Kandoi
aa20df88f5 Merge remote-tracking branch 'origin/version-15-hotfix' into bp15-57647
# Conflicts:
#	erpnext/controllers/sales_and_purchase_return.py
#	erpnext/controllers/tests/test_sales_and_purchase_return.py
2026-08-03 13:30:10 +05:30
Mihir Kandoi
5ec87ae06c chore: resolve conflict 2026-08-03 13:29:37 +05:30
Mihir Kandoi
b4e8aef2f8 Merge pull request #57721 from frappe/mergify/bp/version-15-hotfix/pr-57645
fix(purchase): reject purchase returns where every item has zero quan… (backport #57645)
2026-08-03 13:05:22 +05:30
R-Jayaraman
5152281618 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.

(cherry picked from commit 732c884633)

# Conflicts:
#	erpnext/controllers/tests/test_sales_and_purchase_return.py
2026-08-03 07:34:25 +00:00
R-Jayaraman
48beb2ee23 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.

(cherry picked from commit a3e9d13da3)

# Conflicts:
#	erpnext/controllers/sales_and_purchase_return.py
2026-08-03 07:33:47 +00:00
Mihir Kandoi
198468aa5a test(purchase): fit the backported test to version-15-hotfix
Drop test_sales_return_validates_against_original: it came in with the new
file rather than with the change being backported, covers a raw-SQL to
query-builder conversion that only exists on develop, and imports
erpnext.stock.doctype.delivery_note.mapper, a module this branch does not
have. Base the remaining tests on FrappeTestCase, since ERPNextTestSuite
does not exist here either.
2026-08-03 12:42:14 +05:30
R-Jayaraman
070a7cfb91 test(purchase): add coverage for zero-qty return rejection
(cherry picked from commit cde2963da1)

# Conflicts:
#	erpnext/controllers/tests/test_sales_and_purchase_return.py
2026-08-03 06:16:38 +00:00
R-Jayaraman
8676add875 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.

(cherry picked from commit b63066ed44)
2026-08-03 06:16:37 +00:00
Mihir Kandoi
0f6c6d4df7 Merge pull request #57700 from frappe/mergify/bp/version-15-hotfix/pr-57699
fix: prevent duplicate shipping charges without cost center (backport #57699)
2026-08-02 12:45:29 +05:30
Mihir Kandoi
70da05edb7 fix: resolve version-15 backport conflict 2026-08-02 12:26:50 +05:30
Mihir Kandoi
724eb1aac4 Merge pull request #57696 from frappe/mergify/bp/version-15-hotfix/pr-57674
fix: preserve UOM conversion factor precision in transactions (backport #57674)
2026-08-02 12:23:29 +05:30
Mihir Kandoi
42a2674341 chore: remove shipping rule comments
(cherry picked from commit 106ecd7120)
2026-08-02 06:48:47 +00:00
Mihir Kandoi
a6dff3fc47 fix: prevent duplicate shipping charges without cost center
(cherry picked from commit a4134af30b)

# Conflicts:
#	erpnext/selling/doctype/sales_order/test_sales_order.py
2026-08-02 06:48:47 +00:00
Mihir Kandoi
00df8652e3 fix: resolve version 15 backport conflict 2026-08-02 12:03:47 +05:30
Mihir Kandoi
5a5e20e167 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.

(cherry picked from commit f4d70c2d60)
2026-08-02 06:25:36 +00:00
Mihir Kandoi
4373e295de 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.

(cherry picked from commit 269cc6ee3b)

# Conflicts:
#	erpnext/controllers/taxes_and_totals.py
2026-08-02 06:25:36 +00:00
Diptanil Saha
8bef78afda Merge pull request #57691 from frappe/mergify/bp/version-15-hotfix/pr-57201
fix: permission checks on various whitelisted methods (backport #57201)
2026-08-01 15:45:53 +05:30
Mihir Kandoi
5b47607bc6 Merge pull request #57665 from frappe/mergify/bp/version-15-hotfix/pr-57658
fix: respect quantity precision in material transfer validation (backport #57658)
2026-08-01 15:34:27 +05:30
diptanilsaha
c38c9d5d9b fix(payment_request): added permission checks on resend_payment_email
(cherry picked from commit 0659bd7049)
2026-08-01 15:27:05 +05:30
diptanilsaha
9cd5997500 fix(item_variant): added permission checks on enqueue_multiple_variant_creation
(cherry picked from commit 3b0cbc972e)
2026-08-01 15:26:59 +05:30
diptanilsaha
338fff20db fix(assets): add permission checks on whitelisted methods on asset_capitalization
(cherry picked from commit 09d721d1be)
2026-08-01 15:25:28 +05:30
Sudharsanan11
f9381cc8f9 test: cover material transfer quantity precision
(cherry picked from commit 59bb56aa8d)
2026-08-01 14:37:32 +05:30
Sudharsanan11
a5ed3a5945 fix: respect quantity precision in material transfer validation
(cherry picked from commit eb969a5866)
2026-08-01 14:37:32 +05:30
mergify[bot]
cf42c52530 fix(quotation): carry forward communications from opportunity at after_insert (backport #57639) (#57642)
Co-authored-by: Diptanil Saha <diptanil@frappe.io>
2026-07-31 20:56:17 +05:30
mergify[bot]
42d53783bb fix(plant_floor): add missing perm check on get_stock_summary (backport #57667) (#57669)
Co-authored-by: Diptanil Saha <diptanil@frappe.io>
2026-07-31 15:26:15 +00:00
Mihir Kandoi
276d023946 Merge pull request #57654 from aerele/backport-57567-version-15-hotfix
fix: guard against None row in get_stock_balance_for (backport #57567)
2026-07-31 18:56:31 +05:30
pandiyan
72f293f131 fix: guard against None row in get_stock_balance_for (backport #57567)
get_stock_balance_for() takes row=None by default, but the batch-tracked
branch dereferenced it unconditionally while the two neighbouring row
accesses already guard. Calling it with a batch_no and no row raised
AttributeError: 'NoneType' object has no attribute 'use_serial_batch_fields'.

semgrep's missing-argument-type-hint rule matches the whole function body,
so touching any line inside it re-fingerprints the pre-existing untyped
arguments and reports them as introduced by this PR. Silenced with
nosemgrep instead of annotating: on a whitelisted method the hints are
enforced at runtime by pydantic, which is not a risk worth taking on v15.
2026-07-31 18:08:25 +05:30
mergify[bot]
b826b7c3e6 fix: use payment entry posting date for received amount exchange rate (backport #57660) (#57662)
Co-authored-by: Diptanil Saha <diptanil@frappe.io>
2026-07-31 12:35:48 +00:00
mergify[bot]
b2918b8bb3 feat: make Shipping Rule Cost Center optional with company default fallback (backport #57355) (#57402)
feat: make Shipping Rule Cost Center optional with company default fallback (#57355)

Cost Center on Shipping Rule is no longer mandatory. When left blank, the
applied shipping tax row falls back to the company default cost center,
avoiding the 'Cost Center is required for Profit and Loss account' error on
submit. The rule's project is also applied to the tax row.

(cherry picked from commit a47f25896b)

Co-authored-by: Jatin3128 <jatinsarna8@gmail.com>
2026-07-31 14:51:43 +05:30
Mihir Kandoi
f727f863bb Merge pull request #57020 from frappe/mergify/bp/version-15-hotfix/pr-57015
fix(stock): pick list serial batch posting date (backport #57015)
2026-07-31 13:40:10 +05:30
mergify[bot]
bb36a4fd08 feat: auto-fill subscription accounting dimensions from plan with item fallback (backport #57615) (#57621)
* feat: auto-fill subscription accounting dimensions from plan with item fallback (#57615)

When a plan is selected in the Subscription's Plans table, the Subscription's
accounting dimensions (cost center and any custom dimensions) auto-fill from the
plan, falling back to the plan item's company default (selling cost center for a
Customer, buying for a Supplier). Only empty fields are filled. Stale async
responses are ignored so a quick re-pick of the plan can't be overwritten.

(cherry picked from commit 7febc28ed6)

# Conflicts:
#	erpnext/accounts/doctype/subscription/subscription.js
#	erpnext/accounts/doctype/subscription/subscription.py
#	erpnext/accounts/doctype/subscription/test_subscription.py

* fix: resolve backport merge conflicts for #57615

---------

Co-authored-by: Jatin3128 <140256508+Jatin3128@users.noreply.github.com>
Co-authored-by: Jatin3128 <jatinsarna8@gmail.com>
2026-07-31 12:38:58 +05:30
mergify[bot]
ebf5a462b3 fix: filter Accounts Receivable by invoice sales partner (backport #57628) (#57646)
fix: filter Accounts Receivable by invoice sales partner (#57628)

Filter Accounts Receivable and AR Summary on the Sales Invoice's own
sales_partner instead of the customer's default_sales_partner, and read
the Sales Partner column from the invoice. Returns are attributed to the
invoice they settle, matching how the Sales Person filter works.

(cherry picked from commit fd7765ac02)

Co-authored-by: Jatin3128 <140256508+Jatin3128@users.noreply.github.com>
2026-07-31 12:05:44 +05:30
Mihir Kandoi
bae02a6212 Merge pull request #57242 from frappe/mergify/bp/version-15-hotfix/pr-57223
fix(projects): include on hold status in project filters and reports (backport #57223)
2026-07-31 11:49:50 +05:30
Poovetha
54390bdeb9 fix(projects): add project filter
(cherry picked from commit 7248961568)
2026-07-31 11:09:53 +05:30
Poovetha
82850fb447 test(projects): add test to ensure on hold project retains status
(cherry picked from commit 79e5ccd370)
2026-07-31 11:09:53 +05:30
Poovetha
478426b436 fix(projects): include on hold status in project filters and reports
(cherry picked from commit 51a9fc0316)
2026-07-31 11:09:53 +05:30
ruthra kumar
83837868a0 Merge pull request #57640 from frappe/mergify/bp/version-15-hotfix/pr-57434
fix: update doc status in period closing voucher (backport #57434)
2026-07-31 10:57:12 +05:30
mergify[bot]
972a990b01 fix: do not fetch a random inventory account when multiple inventory accounts exist (backport #57626) (#57631)
* fix: do not fetch a random inventory account when multiple inventory accounts exist (#57626)

(cherry picked from commit 386a4ac1f0)

# Conflicts:
#	erpnext/stock/doctype/purchase_receipt/test_purchase_receipt.py

* chore: fix conflicts

Removed redundant test for valuation taxes in purchase receipt.

* fix: build warehouse account map only when perpetual inventory needs it

For asset purchase receipts or provisional accounting with perpetual
inventory disabled, GL entries do not use warehouse accounts. Building
the full warehouse account map in that case now throws when a company
has multiple inventory accounts and no default, breaking asset receipt
submission. Mirrors the gating on develop.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* test: set default inventory account in valuation taxes LCV test

The conflict resolution kept the pre-backport copy of
test_valuation_taxes_lcv_repost_after_billing, which enables perpetual
inventory on _Test Company without configuring a default inventory
account. The test then failed on submit and leaked the perpetual
inventory flag, breaking every stock test that ran after it in the same
process. Restore the cherry-picked version from #57626.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: rohitwaghchaure <rohitw1991@gmail.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-31 05:11:02 +00:00
nareshkannasln
310b9d4e65 fix: validate account frozen date
(cherry picked from commit b3c2ba5381)
2026-07-31 05:05:37 +00:00
mergify[bot]
68c24f3767 feat: status based bar colors in Work Order gantt view (backport #57634) (#57635)
feat: status based bar colors in Work Order gantt view (#57634)

(cherry picked from commit d59c5e36bc)

Co-authored-by: rohitwaghchaure <rohitw1991@gmail.com>
2026-07-31 09:59:07 +05:30
Mihir Kandoi
f2ec60b7a5 Merge pull request #57629 from frappe/mergify/bp/version-15-hotfix/pr-57616
fix: seed standard Item Groups under the existing tree root (backport #57616)
2026-07-30 19:46:00 +05:30
Mihir Kandoi
1602639a80 fix: resolve backport conflicts for version-15
install() holds the preset list inline on this branch, so the root is
resolved there instead of in get_preset_records. Dropping the preset-record
test with it -- there is no seam to call without running the whole installer.

The patch test is adapted to this branch: TestItem does not roll back between
tests, so it restores the original root name, and it passes parent_item_group
explicitly since ItemGroup.validate skips root-defaulting under
frappe.flags.in_test.
2026-07-30 19:22:29 +05:30
Mihir Kandoi
848335086c fix: seed standard Item Groups under the existing tree root
install_fixtures always inserted "All Item Groups" as a parentless group.
On a site where another app had already created the root, ItemGroup.validate
re-parented it, leaving a second group-root that held the standard groups
while the real root held everything else.

This is reproducible with the healthcare app on a non-English site: its
after_install seeds the root as _("All Item Groups"), so a pt-BR site gets
"Todos os Grupos de Itens" as the root before the setup wizard runs. The
split predates #57390 -- the old translated-name lookup resolved to the same
root and produced an identical tree.

Resolve the root once with get_root_of (falling back to the canonical English
name on fresh installs) and use it for the root record's exists-guard and the
standard groups' parent, matching Company.create_default_departments.

Patch merges an already-seeded "All Item Groups" into the root it sits under,
lifting its children and repointing every link.

Closes #57581

(cherry picked from commit e7088d8981)

# Conflicts:
#	erpnext/setup/doctype/item_group/test_item_group.py
#	erpnext/setup/setup_wizard/operations/install_fixtures.py
2026-07-30 13:41:45 +00:00
Shllokkk
9a596594da Merge pull request #57619 from Shllokkk/asset-manual-create-valuation-rate-v15
fix: source manually created asset value from valuation rate
2026-07-30 14:58:42 +05:30
Shllokkk
455d6d4ac1 fix: source manually created asset value from valuation rate 2026-07-30 14:31:54 +05:30
mergify[bot]
7cecff9fa4 fix: let Purchase Receipt cancel defer to Frappe's linked-document check (backport #57592) (#57602)
fix: let Purchase Receipt cancel defer to Frappe's linked-document check (#57592)

on_cancel pre-blocked cancellation with its own "Purchase Invoice is
already submitted" guard, duplicating the check Frappe already runs for any
submitted linked document. Drop the guard and the unused check_next_docstatus()
method it mirrored so the receipt defers to the framework: the Cancel All
Documents flow cancels the invoice first and then the receipt, and a direct
cancel is still rejected by Frappe's linked-document check.

Add a regression test that a direct cancel of a receipt with a submitted
invoice is rejected and rolls back, leaving no stray stock or GL entries.

(cherry picked from commit cfe18e8427)

# Conflicts:
#	erpnext/stock/doctype/purchase_receipt/purchase_receipt.py
#	erpnext/stock/doctype/purchase_receipt/test_purchase_receipt.py

Co-authored-by: Jatin3128 <140256508+Jatin3128@users.noreply.github.com>
2026-07-30 12:41:53 +05:30
mergify[bot]
94d63ebb49 fix(stock): value batched packed-item returns from the original bundle (backport #57327) (#57510)
fix(stock): value batched packed-item returns from the original bundle  (#57327)

* fix(stock): value batched packed-item returns from the original bundle

when a return delivery note or sales invoice bundle is built via the
use_serial_batch_fields / sle-driven path, its voucher_detail_no keeps the
packed item instead of being remapped to the parent dn/si item. the return
valuation lookup then misses and the bundle values at zero, so the sle
stock_value_difference stays wrong even after a repost.

resolve the original dn/si item via the packed item's parent_detail_docname
when the direct lookup fails, so the return values from the original outward
bundle on both submit and repost.

* test(stock): cover batched packed-item return valuation on repost

(cherry picked from commit d37e905322)

Co-authored-by: Sudharsanan Ashok <135326972+Sudharsanan11@users.noreply.github.com>
2026-07-30 07:02:41 +00:00
Frappe PR Bot
7098602dcc chore(release): Bumped to Version 15.118.3
## [15.118.3](https://github.com/frappe/erpnext/compare/v15.118.2...v15.118.3) (2026-07-30)

### Bug Fixes

* **italy:** skip e-invoicing for opening invoices ([4f07e25](4f07e2503b))
* **stock:** keep manufactured item rate at zero when inputs are free  (backport [#57334](https://github.com/frappe/erpnext/issues/57334)) ([#57512](https://github.com/frappe/erpnext/issues/57512)) ([ade3f79](ade3f791a4))
2026-07-30 05:19:18 +00:00
Diptanil Saha
32b56ac505 Merge pull request #57611 from frappe/version-15-hotfix
chore: release v15
2026-07-30 10:47:30 +05:30
mergify[bot]
9f1bdba9a7 refactor(accounts): repost accounting ledger (backport #56442) (#57598)
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Diptanil Saha <diptanil@frappe.io>
2026-07-30 10:15:40 +05:30
mergify[bot]
ade3f791a4 fix(stock): keep manufactured item rate at zero when inputs are free (backport #57334) (#57512)
fix(stock): keep manufactured item rate at zero when inputs are free  (#57334)

* fix(stock): keep manufactured item rate at zero when inputs are free

when a finished item is produced from raw materials consumed at zero
valuation, the incoming rate fell back to the item's own valuation
rate (or BOM cost), valuing free inputs as output and inflating the fg
value on every production run.

add has_consumption_basis() to detect when the consumed cost is known
even if it is zero (consumed rows present, or a consumption entry
exists for the work order). when it is, skip the get_valuation_rate and
BOM-cost fallbacks so a real cost of zero is preserved.

* test(stock): cover manufacture rate for zero-valued raw materials

- manufacture from a free input keeps fg basic_rate and sle
  incoming_rate/stock_value_difference at zero even when the fg already
  carries a valuation in the target warehouse
- material consumption on with no consumption entry does not fall back
  to bom/price-list rate for free inputs
- zero-valued consumption entry keeps the manufacture entry's fg rate
  at zero

(cherry picked from commit 73224d3650)

Co-authored-by: Sudharsanan Ashok <135326972+Sudharsanan11@users.noreply.github.com>
2026-07-30 09:25:52 +05:30
mergify[bot]
967955a926 refactor(accounts): repost accounting ledger (backport #56442) (#57584)
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Diptanil Saha <diptanil@frappe.io>
2026-07-29 15:23:30 +05:30
Krishna Pramod Shirsath
71b5f41556 Merge pull request #57589 from frappe/mergify/bp/version-15-hotfix/pr-57314
fix(italy): skip e-invoicing for opening invoices (backport #57314)
2026-07-29 13:44:08 +05:30
Krishna Shirsath
4f07e2503b fix(italy): skip e-invoicing for opening invoices
(cherry picked from commit f328018bfb)
2026-07-29 05:39:23 +00:00
Mihir Kandoi
16e14d70b5 Merge pull request #57586 from aerele/backport-57335-version-15-hotfix
refactor: reuse shared date range validation across reports
2026-07-29 10:46:55 +05:30
pandiyan
33d3696385 refactor: reuse shared date range validation across reports 2026-07-29 06:12:43 +05:30
Pandiyan P
a51750db56 fix(stock): pick list serial batch posting date (#57015)
* fix(stock): fall back to current date/time for serial and batch bundle posting datetime

Pick List has no posting_date/posting_time fields, so creating or updating a
Serial and Batch Bundle from a Pick List row crashed with
"TypeError: combine() argument 1 must be datetime.date, not None". Fall back
to today/now when the parent voucher doesn't carry its own posting date.

Fixes #56951

* fix(stock): accept a plain dict for add_serial_batch_ledgers' doc and child_row

The whitelisted add_serial_batch_ledgers only converted child_row into an
attribute-accessible frappe._dict when it arrived as a JSON string, and doc's
type hint only allowed Document | str. Frappe's JSON API delivers both as
plain dicts (see frappe.app.make_form_dict, which parses the request body
with orjson and only wraps the top-level dict, not nested values), so every
real request was rejected before the handler body ever ran: first with a
FrappeTypeError on doc, and once that's fixed, with an AttributeError on
child_row.serial_and_batch_bundle. parse_json already wraps a plain dict in
frappe._dict (and leaves a real Document instance untouched), so routing
child_row through it unconditionally fixes both.

(cherry picked from commit 7e46be2a33)
2026-07-10 06:11:45 +00:00
321 changed files with 18535 additions and 3191 deletions

View File

@@ -4,7 +4,7 @@ import inspect
import frappe
from frappe.utils.user import is_website_user
__version__ = "15.118.2"
__version__ = "15.121.3"
def get_default_company(user=None):

View File

@@ -65,4 +65,6 @@ def get_shipping_address(company, address=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

@@ -24,7 +24,8 @@
"account_number": "11530"
},
"account_number": "115",
"is_group": 1
"is_group": 1,
"account_type": "Bank"
},
"Trade Receivables": {
"Trade Debtors": {
@@ -529,6 +530,13 @@
"account_number": "630",
"is_group": 1
},
"Accrued Manufacturing Expenses": {
"Accrued Expenses - Manufacturing": {
"account_number": "63510"
},
"account_number": "635",
"is_group": 1
},
"account_number": "63",
"is_group": 1
},
@@ -814,4 +822,4 @@
"root_type": "Expense"
}
}
}
}

View File

@@ -89,13 +89,14 @@
"enable_fuzzy_matching",
"reports_tab",
"remarks_section",
"general_ledger_remarks_length",
"disable_include_dimensions",
"column_break_lvjk",
"receivable_payable_remarks_length",
"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",
"payment_request_settings",
@@ -222,7 +223,8 @@
"description": "The percentage you are allowed to bill more against the amount ordered. For example, if the order value is $100 for an item and tolerance is set as 10%, then you are allowed to bill up to $110 ",
"fieldname": "over_billing_allowance",
"fieldtype": "Currency",
"label": "Over Billing Allowance (%)"
"label": "Over Billing Allowance (%)",
"non_negative": 1
},
{
"default": "1",
@@ -483,7 +485,7 @@
{
"fieldname": "remarks_section",
"fieldtype": "Section Break",
"label": "Remarks Column Length"
"label": "General Ledger Report"
},
{
"default": "0",
@@ -566,7 +568,7 @@
{
"fieldname": "accounts_receivable_payable_tuning_section",
"fieldtype": "Section Break",
"label": "Accounts Receivable / Payable Tuning"
"label": "Accounts Receivable / Payable Report"
},
{
"fieldname": "legacy_section",
@@ -665,6 +667,12 @@
"fieldname": "default_ageing_range",
"fieldtype": "Data",
"label": "Default Ageing Range"
},
{
"default": "0",
"fieldname": "disable_include_dimensions",
"fieldtype": "Check",
"label": "Disable \"Consider Accounting Dimension\" Filter"
}
],
"icon": "icon-cog",
@@ -672,7 +680,7 @@
"index_web_pages_for_search": 1,
"issingle": 1,
"links": [],
"modified": "2026-06-24 12:59:41.868865",
"modified": "2026-09-04 10:08:30.115003",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Accounts Settings",

View File

@@ -44,6 +44,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_common_party_accounting: DF.Check
enable_fuzzy_matching: DF.Check
enable_immutable_ledger: DF.Check

View File

@@ -94,11 +94,11 @@
"fieldtype": "Column Break"
},
{
"allow_on_submit": 1,
"fieldname": "project",
"fieldtype": "Link",
"label": "Project",
"options": "Project"
"allow_on_submit": 1,
"fieldname": "project",
"fieldtype": "Link",
"label": "Project",
"options": "Project"
},
{
"fieldname": "section_break_8",
@@ -187,12 +187,14 @@
"index_web_pages_for_search": 1,
"istable": 1,
"links": [],
"modified": "2021-11-25 11:10:10.945027",
"modified": "2026-05-01 00:38:53.368737",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Advance Taxes and Charges",
"owner": "Administrator",
"permissions": [],
"row_format": "Dynamic",
"sort_field": "modified",
"sort_order": "ASC"
}
"sort_order": "ASC",
"states": []
}

View File

@@ -30,6 +30,7 @@ class AdvanceTaxesandCharges(Document):
parent: DF.Data
parentfield: DF.Data
parenttype: DF.Data
project: DF.Link | None
rate: DF.Float
row_id: DF.Data | None
tax_amount: DF.Currency

View File

@@ -105,25 +105,30 @@ class BankStatementImport(DataImport):
@frappe.whitelist()
def get_preview_from_template(data_import, import_file=None, google_sheets_url=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):
return frappe.get_doc("Bank Statement Import", data_import).start_import()
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):
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):
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 parse_data_from_template(raw_data):
@@ -252,6 +257,7 @@ def get_import_status(docname):
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

@@ -98,13 +98,13 @@ class Budget(Document):
frappe.throw(_("Budget cannot be assigned against Group Account {0}").format(d.account))
elif account_details.company != self.company:
frappe.throw(
_("Account {0} does not belongs to company {1}").format(d.account, self.company)
_("Account {0} does not belong to company {1}").format(d.account, self.company)
)
elif account_details.report_type != "Profit and Loss":
frappe.throw(
_(
"Budget cannot be assigned against {0}, as its Root Type is not of Income or Expense"
).format(self.account)
).format(d.account)
)
if d.account in account_list:

View File

@@ -357,6 +357,16 @@ class TestBudget(unittest.TestCase):
self.assertRaises(BudgetError, jv.submit)
def test_budget_against_balance_sheet_account(self):
budget = frappe.new_doc("Budget")
budget.budget_against = "Cost Center"
budget.cost_center = "_Test Cost Center - _TC"
budget.company = "_Test Company"
budget.fiscal_year = get_fiscal_year(nowdate())[0]
budget.append("accounts", {"account": "_Test Bank - _TC", "budget_amount": 200000})
self.assertRaisesRegex(frappe.ValidationError, "_Test Bank - _TC", budget.insert)
def set_total_expense_zero(posting_date, budget_against_field=None, budget_against_CC=None):
if budget_against_field == "project":

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,22 +70,37 @@ def validate_company(company):
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()
def import_coa(file_name, company):
frappe.only_for("Accounts Manager")
# delete existing data for accounts
unset_existing_data(company)
frappe.has_permission("Company", "write", company, throw=True)
# 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)
@@ -452,6 +467,7 @@ def unset_existing_data(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}
frappe.db.set_value("Company", company, update_values, update_values)
# remove accounts data from various doctypes
@@ -467,6 +483,19 @@ def unset_existing_data(company):
frappe.qb.from_(dt).where(dt.company == company).delete().run()
def validate_user_perms(company):
# User Permission Check for Account Deletion
company_accounts = frappe.get_query("Account", filters={"company": company}).run(as_dict=1)
for d in company_accounts:
if not frappe.get_cached_doc("Account", d.name).has_permission():
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):
from erpnext.setup.doctype.company.company import install_country_fixtures

View File

@@ -234,8 +234,10 @@ frappe.ui.form.on("Dunning", {
dn: frm.doc.name,
},
callback: function (r) {
var doc = frappe.model.sync(r.message);
frappe.set_route("Form", doc[0].doctype, doc[0].name);
if (!r.exc) {
var doc = frappe.model.sync(r.message);
frappe.set_route("Form", doc[0].doctype, doc[0].name);
}
},
});
},

View File

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

View File

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

View File

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

View File

@@ -168,7 +168,7 @@
}
],
"is_submittable": 1,
"modified": "2019-05-30 19:08:21.199759",
"modified": "2026-09-09 17:04:59.512294",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Invoice Discounting",
@@ -185,7 +185,7 @@
"print": 1,
"read": 1,
"report": 1,
"role": "System Manager",
"role": "Accounts Manager",
"share": 1,
"submit": 1,
"write": 1
@@ -194,4 +194,4 @@
"sort_field": "modified",
"sort_order": "DESC",
"track_changes": 1
}
}

View File

@@ -319,6 +319,13 @@ class InvoiceDiscounting(AccountsController):
@frappe.whitelist()
def get_invoices(filters):
filters = frappe._dict(json.loads(filters))
if not filters.get("company"):
frappe.throw(_("Please set company on the Document before requesting for invoices."))
frappe.has_permission("Company", doc=filters.get("company"), throw=True)
frappe.has_permission("Invoice Discounting", throw=True)
cond = []
if filters.customer:
cond.append("customer=%(customer)s")

View File

@@ -47,3 +47,12 @@ frappe.ui.form.on("Item Tax Template", {
});
},
});
frappe.ui.form.on("Item Tax Template Detail", {
not_applicable: function (frm, cdt, cdn) {
let row = locals[cdt][cdn];
if (row.not_applicable) {
frappe.model.set_value(cdt, cdn, "tax_rate", 0);
}
},
});

View File

@@ -27,8 +27,15 @@ class ItemTaxTemplate(Document):
# end: auto-generated types
def validate(self):
self.set_zero_rate_for_not_applicable_tax()
self.validate_tax_accounts()
def set_zero_rate_for_not_applicable_tax(self):
"""Ensure tax_rate is 0 for any row marked as not applicable."""
for row in self.get("taxes"):
if row.not_applicable:
row.tax_rate = 0
def autoname(self):
if self.company and self.title:
abbr = frappe.get_cached_value("Company", self.company, "abbr")

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

@@ -3,6 +3,142 @@
import unittest
import frappe
from frappe.tests.utils import FrappeTestCase
from erpnext.patches.v16_0.set_not_applicable_on_german_item_tax_templates import (
execute as backfill_not_applicable,
)
class TestItemTaxTemplate(unittest.TestCase):
pass
class TestGermanNotApplicableBackfill(FrappeTestCase):
"""Run the `not_applicable` backfill patch against a seeded German company.
The company is created from the shipped German defaults, so the templates the
patch has to recognise are the ones a real site got. Each test resets the flag
to its pre-patch state (`not_applicable = 0`) and runs the patch.
"""
TITLES = ("19 %", "7 %", "0%")
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.company = "_Test German Item Tax Templates"
if not frappe.db.exists("Company", cls.company):
frappe.get_doc(
{
"doctype": "Company",
"company_name": cls.company,
"abbr": "_TGITT",
"country": "Germany",
"default_currency": "EUR",
"create_chart_of_accounts_based_on": "Standard Template",
"chart_of_accounts": "Standard",
}
).insert()
cls.templates = {
title: frappe.db.get_value("Item Tax Template", {"company": cls.company, "title": title}, "name")
for title in cls.TITLES
}
assert all(cls.templates.values()), f"German defaults not seeded: {cls.templates}"
def setUp(self):
frappe.db.savepoint("before_backfill_test")
self.addCleanup(frappe.db.rollback, save_point="before_backfill_test")
self.seeded_flags = self.flagged_rows()
# every default template ships not-applicable rows, otherwise the patch
# would be tested against effectively empty data
for title in self.TITLES:
self.assertTrue(self.seeded_flags[title], f"no not-applicable rows seeded in {title}")
def flagged_rows(self, title=None) -> dict[str, set]:
"""Detail rows currently marked as not applicable, per template title."""
return {
t: {
d.name
for d in frappe.get_all(
"Item Tax Template Detail",
filters={"parent": name, "not_applicable": 1},
fields=["name"],
)
}
for t, name in self.templates.items()
if title in (None, t)
}
def clear_flags(self):
"""Restore the pre-patch state: zero rate, no flag."""
for name in self.templates.values():
frappe.db.set_value(
"Item Tax Template Detail",
{"parent": name},
"not_applicable",
0,
update_modified=False,
)
self.assertEqual(self.flagged_rows(), {t: set() for t in self.TITLES})
def add_zero_rate_row(self, title, account_name, account_number):
"""Add a user-defined zero-rate row, as a customised site would have."""
like_account = frappe.db.get_value(
"Account", {"company": self.company, "account_name": "Umsatzsteuer 19 %"}, "name"
)
account = frappe.get_doc(
{
"doctype": "Account",
"company": self.company,
"account_name": account_name,
"account_number": account_number,
"account_type": "Tax",
"parent_account": frappe.db.get_value("Account", like_account, "parent_account"),
}
).insert()
template = frappe.get_doc("Item Tax Template", self.templates[title])
template.append("taxes", {"tax_type": account.name, "tax_rate": 0})
template.save()
def test_backfills_unmodified_defaults(self):
self.clear_flags()
backfill_not_applicable()
self.assertEqual(self.flagged_rows(), self.seeded_flags)
def test_keeps_customised_template_untouched(self):
self.clear_flags()
self.add_zero_rate_row("19 %", "Sonstige Umsatzsteuer", "9998")
backfill_not_applicable()
self.assertEqual(self.flagged_rows("19 %"), {"19 %": set()})
self.assertEqual(self.flagged_rows("7 %"), {"7 %": self.seeded_flags["7 %"]})
def test_keeps_duplicate_account_name_untouched(self):
"""A numbered account can share `account_name` with a default one.
Its identifier collapses onto the default's, so only the row count tells
the customised template apart from an untouched one.
"""
self.clear_flags()
self.add_zero_rate_row("7 %", "Umsatzsteuer 19 %", "9999")
backfill_not_applicable()
self.assertEqual(self.flagged_rows("7 %"), {"7 %": set()})
self.assertEqual(self.flagged_rows("19 %"), {"19 %": self.seeded_flags["19 %"]})
def test_rerun_changes_nothing(self):
def snapshot():
return frappe.get_all(
"Item Tax Template Detail",
filters={"parent": ("in", tuple(self.templates.values()))},
fields=["name", "not_applicable", "tax_rate", "modified"],
order_by="name",
)
before = snapshot()
backfill_not_applicable()
self.assertEqual(snapshot(), before)

View File

@@ -6,7 +6,8 @@
"engine": "InnoDB",
"field_order": [
"tax_type",
"tax_rate"
"tax_rate",
"not_applicable"
],
"fields": [
{
@@ -21,12 +22,21 @@
"fieldname": "tax_rate",
"fieldtype": "Float",
"in_list_view": 1,
"label": "Tax Rate"
"label": "Tax Rate",
"read_only_depends_on": "eval:doc.not_applicable"
},
{
"default": "0",
"description": "Check if this tax is not applicable to items (distinct from 0% rate)",
"fieldname": "not_applicable",
"fieldtype": "Check",
"in_list_view": 1,
"label": "Not Applicable"
}
],
"istable": 1,
"links": [],
"modified": "2026-04-30 23:49:27.020639",
"modified": "2026-04-30 23:59:22.020639",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Item Tax Template Detail",

View File

@@ -14,6 +14,7 @@ class ItemTaxTemplateDetail(Document):
if TYPE_CHECKING:
from frappe.types import DF
not_applicable: DF.Check
parent: DF.Data
parentfield: DF.Data
parenttype: DF.Data

View File

@@ -65,7 +65,7 @@ frappe.ui.form.on("Journal Entry", {
);
}
if (frm.doc.docstatus == 1) {
if (frm.doc.docstatus == 1 && !frm.doc.reversal_of) {
frm.add_custom_button(
__("Reverse Journal Entry"),
function () {
@@ -421,8 +421,8 @@ cur_frm.cscript.update_totals = function (doc) {
tc += flt(accounts[i].credit, precision("credit", accounts[i]));
}
doc = locals[doc.doctype][doc.name];
doc.total_debit = td;
doc.total_credit = tc;
doc.total_debit = flt(td, precision("total_debit"));
doc.total_credit = flt(tc, precision("total_credit"));
doc.difference = flt(td - tc, precision("difference"));
refresh_many(["total_debit", "total_credit", "difference"]);
};
@@ -516,7 +516,7 @@ $.extend(erpnext.journal_entry, {
lock_reversal_entry: function (frm) {
frm.fields
.filter((field) => field.has_input)
.filter((field) => field.df.fieldname != "posting_date")
.filter((field) => !["posting_date", "user_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);
},

View File

@@ -7,7 +7,8 @@ import json
import frappe
from frappe import _, msgprint, scrub
from frappe.core.doctype.submission_queue.submission_queue import queue_submission
from frappe.utils import comma_and, cstr, flt, fmt_money, formatdate, get_link_to_form, nowdate
from frappe.model.document import Document
from frappe.utils import comma_and, cstr, flt, fmt_money, formatdate, get_link_to_form, getdate, nowdate
import erpnext
from erpnext.accounts.deferred_revenue import get_deferred_booking_accounts
@@ -154,7 +155,8 @@ class JournalEntry(AccountsController):
if self.docstatus == 0:
self.apply_tax_withholding()
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):
@@ -798,6 +800,23 @@ class JournalEntry(AccountsController):
)
)
if reference_type == "Purchase Invoice":
on_hold, release_date = frappe.db.get_value(
reference_type, reference_name, ["on_hold", "release_date"]
)
if not on_hold or (release_date and getdate(release_date) <= getdate(nowdate())):
continue
msg = (
_("{0} {1} is blocked and on hold until {2}.").format(
reference_type, reference_name, release_date
)
if release_date
else _("{0} {1} is blocked.").format(reference_type, reference_name)
)
frappe.throw(msg)
def set_against_account(self):
accounts_debited, accounts_credited = [], []
if self.voucher_type in ("Deferred Revenue", "Deferred Expense"):
@@ -842,12 +861,14 @@ class JournalEntry(AccountsController):
if d.debit and d.credit:
frappe.throw(_("You cannot credit and debit same account at the same time"))
self.total_debit = flt(self.total_debit) + flt(d.debit, d.precision("debit"))
self.total_credit = flt(self.total_credit) + flt(d.credit, d.precision("credit"))
self.total_debit = flt(
self.total_debit + flt(d.debit, d.precision("debit")), self.precision("total_debit")
)
self.total_credit = flt(
self.total_credit + flt(d.credit, d.precision("credit")), self.precision("total_credit")
)
self.difference = flt(self.total_debit, self.precision("total_debit")) - flt(
self.total_credit, self.precision("total_credit")
)
self.difference = flt(self.total_debit - self.total_credit, self.precision("difference"))
def validate_multi_currency(self):
alternate_currency = []
@@ -1507,6 +1528,7 @@ def get_payment_entry_against_order(
dt, dn, amount=None, debit_in_account_currency=None, journal_entry=False, bank_account=None
):
ref_doc = frappe.get_doc(dt, dn)
ref_doc.check_permission()
if flt(ref_doc.per_billed, 2) > 0:
frappe.throw(_("Can only make payment against unbilled {0}").format(dt))
@@ -1552,6 +1574,8 @@ def get_payment_entry_against_invoice(
dt, dn, amount=None, debit_in_account_currency=None, journal_entry=False, bank_account=None
):
ref_doc = frappe.get_doc(dt, dn)
ref_doc.check_permission()
if dt == "Sales Invoice":
party_type = "Customer"
party_account = get_party_account_based_on_invoice_discounting(dn) or ref_doc.debit_to
@@ -1587,6 +1611,8 @@ def get_payment_entry_against_invoice(
def get_payment_entry(ref_doc, args):
frappe.has_permission("Journal Entry", ptype="create", throw=True)
cost_center = ref_doc.get("cost_center") or frappe.get_cached_value(
"Company", ref_doc.company, "cost_center"
)
@@ -1874,7 +1900,21 @@ def make_inter_company_journal_entry(name, voucher_type, company):
@frappe.whitelist()
def make_reverse_journal_entry(source_name, target_doc=None):
def make_reverse_journal_entry(source_name: str, target_doc: str | dict | Document | None = None) -> Document:
# `get_mapped_doc` checks this as well, but the guard below discloses which entry
# reverses which, so read access has to be settled before it runs
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),
)
)
from frappe.model.mapper import get_mapped_doc
def post_process(source, target):

View File

@@ -6,7 +6,7 @@ import unittest
import frappe
from frappe.tests.utils import change_settings
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
@@ -249,6 +249,27 @@ class TestJournalEntry(unittest.TestCase):
self.check_gl_entries()
def test_disallow_reversal_of_a_reversal_journal_entry(self):
from erpnext.accounts.doctype.journal_entry.journal_entry 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)
@@ -389,6 +410,59 @@ class TestJournalEntry(unittest.TestCase):
self.check_gl_entries()
def make_jv_with_fractional_totals(self):
"""0.10 + 0.20 sums to 0.30000000000000004, the residue this guards against."""
jv = frappe.new_doc("Journal Entry")
jv.posting_date = nowdate()
jv.company = "_Test Company"
jv.voucher_type = "Journal Entry"
jv.remark = "test"
for amount in (0.10, 0.20):
jv.append(
"accounts",
{
"account": "_Test Cash - _TC",
"cost_center": "_Test Cost Center - _TC",
"debit_in_account_currency": amount,
},
)
jv.append(
"accounts",
{
"account": "_Test Bank - _TC",
"cost_center": "_Test Cost Center - _TC",
"credit_in_account_currency": 0.30,
},
)
jv.insert()
return jv
def test_totals_are_rounded_to_precision(self):
jv = self.make_jv_with_fractional_totals()
jv.submit()
stored = frappe.db.get_value(
"Journal Entry", jv.name, ["total_debit", "total_credit", "difference"], as_dict=True
)
self.assertEqual(jv.total_debit, flt(jv.total_debit, jv.precision("total_debit")))
self.assertEqual(jv.total_credit, flt(jv.total_credit, jv.precision("total_credit")))
self.assertEqual(jv.total_debit, stored.total_debit)
self.assertEqual(jv.total_credit, stored.total_credit)
self.assertEqual(jv.difference, stored.difference)
def test_update_after_submit_with_fractional_totals(self):
"""An unrounded total is stored rounded, so updating a submitted entry used to throw."""
jv = self.make_jv_with_fractional_totals()
jv.submit()
jv.pay_to_recd_from = "_Test Supplier"
jv.save()
self.assertEqual(jv.docstatus, 1)
self.assertEqual(
jv.pay_to_recd_from, frappe.db.get_value("Journal Entry", jv.name, "pay_to_recd_from")
)
def test_jv_account_and_party_balance_with_cost_centre(self):
from erpnext.accounts.doctype.cost_center.test_cost_center import create_cost_center
from erpnext.accounts.utils import get_balance_on
@@ -602,6 +676,69 @@ class TestJournalEntry(unittest.TestCase):
jv.save()
self.assertRaises(frappe.ValidationError, jv.submit)
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", 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 make_journal_entry(
account1,

View File

@@ -56,7 +56,9 @@ class LedgerMerge(Document):
@frappe.whitelist()
def form_start_merge(docname):
return frappe.get_doc("Ledger Merge", docname).start_merge()
lm_doc = frappe.get_doc("Ledger Merge", docname)
lm_doc.check_permission("write")
return lm_doc.start_merge()
def start_merge(docname):

View File

@@ -282,6 +282,9 @@ def start_import(invoices):
invoice_number = d.invoice_number
doc = frappe.get_doc(d)
doc.flags.ignore_mandatory = True
# the outstanding amount is entered inclusive of tax, so taxes must not
# be added on top of it
doc.flags.dont_auto_add_taxes = True
doc.insert(set_name=invoice_number)
doc.submit()
frappe.db.commit()

View File

@@ -2,9 +2,10 @@
# See license.txt
import frappe
from frappe.tests.utils import FrappeTestCase
from frappe.tests.utils import FrappeTestCase, change_settings
from frappe.utils import add_days, today
from erpnext.accounts.doctype.account.test_account import create_account
from erpnext.accounts.doctype.accounting_dimension.test_accounting_dimension import (
create_dimension,
disable_dimension,
@@ -12,6 +13,7 @@ from erpnext.accounts.doctype.accounting_dimension.test_accounting_dimension imp
from erpnext.accounts.doctype.opening_invoice_creation_tool.opening_invoice_creation_tool import (
get_temporary_opening_account,
)
from erpnext.accounts.doctype.tax_rule.test_tax_rule import make_tax_rule
from erpnext.projects.doctype.project.test_project import make_project
test_dependencies = ["Customer", "Supplier", "Accounting Dimension"]
@@ -140,6 +142,55 @@ class TestOpeningInvoiceCreationTool(FrappeTestCase):
for invoice in invoices:
self.assertEqual(frappe.db.get_value("Sales Invoice", invoice, "department"), "Sales - _TOIC")
@change_settings(
"Accounts Settings",
{"add_taxes_from_taxes_and_charges_template": 1, "add_taxes_from_item_tax_template": 0},
)
def test_opening_invoice_creation_without_taxes(self):
company = "_Test Opening Invoice Company"
template = frappe.get_doc(
{
"doctype": "Sales Taxes and Charges Template",
"company": company,
"title": "_Test Opening Invoice Tax",
"taxes": [
{
"charge_type": "On Net Total",
"account_head": create_account(
account_name="_Test Opening Tax Account",
parent_account="Duties and Taxes - _TOIC",
account_type="Tax",
company=company,
),
"description": "Test taxes",
"rate": 9,
}
],
}
).insert()
# makes the template the default for the party, as it would be on a live site
make_tax_rule(tax_type="Sales", company=company, sales_tax_template=template.name, save=1)
tool = self.make_invoices(company=company, return_doc=True)
invoices = tool.make_invoices()
self.assertEqual(len(invoices), 2)
# outstanding amount is entered inclusive of tax, so taxes must not be added on top of it
for invoice in invoices:
si = frappe.get_doc("Sales Invoice", invoice)
self.assertFalse(si.taxes)
self.assertEqual(si.grand_total, 200)
self.assertEqual(si.outstanding_amount, 200)
# the same invoice created outside the tool keeps the default taxes,
# since adding them there is the user's decision
si = frappe.get_doc(tool.get_invoices()[0])
si.flags.ignore_mandatory = True
si.insert()
self.assertTrue(si.taxes)
self.assertEqual(si.grand_total, 218)
def test_opening_entry_project_linking(self):
doc = self.make_invoices(
company="_Test Opening Invoice Company", invoice_type="Sales", return_doc=True

View File

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

View File

@@ -3,6 +3,7 @@
import json
from datetime import date
from functools import reduce
import frappe
@@ -90,6 +91,7 @@ class PaymentEntry(AccountsController):
self.set_liability_account()
self.set_missing_ref_details(force=True)
self.validate_payment_type()
self.validate_internal_transfer_accounts()
self.validate_party_details()
self.set_exchange_rate()
self.validate_mandatory()
@@ -121,8 +123,14 @@ class PaymentEntry(AccountsController):
self.update_payment_schedule()
self.make_gl_entries()
self.update_outstanding_amounts()
self.update_linked_dunnings()
self.set_status()
def update_linked_dunnings(self):
from erpnext.accounts.doctype.dunning.dunning import update_dunnings_linked_to_payment
update_dunnings_linked_to_payment(self)
def validate_for_repost(self):
validate_docs_for_voucher_types(["Payment Entry"])
validate_docs_for_deferred_accounting([self.name], [])
@@ -224,6 +232,7 @@ class PaymentEntry(AccountsController):
self.update_payment_schedule(cancel=1)
self.make_gl_entries(cancel=1)
self.update_outstanding_amounts()
self.update_linked_dunnings()
self.delink_advance_entry_references()
self.set_status()
@@ -531,6 +540,10 @@ class PaymentEntry(AccountsController):
if self.payment_type not in ("Receive", "Pay", "Internal Transfer"):
frappe.throw(_("Payment Type must be one of Receive, Pay and Internal Transfer"))
def validate_internal_transfer_accounts(self):
if self.payment_type == "Internal Transfer" and self.paid_from and self.paid_from == self.paid_to:
frappe.throw(_("Paid From and Paid To accounts must be different for an Internal Transfer."))
def validate_party_details(self):
if self.party and not frappe.db.exists(self.party_type, self.party):
frappe.throw(_("{0} {1} does not exist").format(_(self.party_type), self.party))
@@ -1301,8 +1314,14 @@ class PaymentEntry(AccountsController):
self.add_deductions_gl_entries(gl_entries)
self.add_tax_gl_entries(gl_entries)
add_regional_gl_entries(gl_entries, self)
self.set_transaction_currency_and_rate_in_gl_map(gl_entries)
return gl_entries
def set_transaction_currency_and_rate_in_gl_map(self, gl_entries):
for gle in gl_entries:
gle.setdefault("transaction_currency", self.transaction_currency)
gle.setdefault("transaction_exchange_rate", self.transaction_exchange_rate)
def make_gl_entries(self, cancel=0, adv_adj=0):
gl_entries = self.build_gl_map()
gl_entries = process_gl_map(gl_entries)
@@ -2880,18 +2899,21 @@ def get_reference_details(
@frappe.whitelist()
def get_payment_entry(
dt,
dn,
party_amount=None,
bank_account=None,
bank_amount=None,
party_type=None,
payment_type=None,
reference_date=None,
ignore_permissions=False,
created_from_payment_request=False,
dt: str,
dn: str,
party_amount: int | float | None = None,
bank_account: str | None = None,
bank_amount: int | float | None = None,
party_type: str | None = None,
payment_type: str | None = None,
reference_date: str | date | None = None,
created_from_payment_request: bool | None = False,
):
frappe.has_permission("Payment Entry", ptype="create", throw=True)
doc = frappe.get_doc(dt, dn)
doc.check_permission()
over_billing_allowance = frappe.db.get_single_value("Accounts Settings", "over_billing_allowance")
if dt in ("Sales Order", "Purchase Order") and flt(doc.per_billed, 2) >= (100.0 + over_billing_allowance):
frappe.throw(_("Can only make payment against unbilled {0}").format(_(dt)))
@@ -2986,7 +3008,7 @@ def get_payment_entry(
pe.append("references", reference)
else:
if dt == "Dunning":
for overdue_payment in doc.overdue_payments:
for overdue_payment, outstanding in doc.get_unpaid_overdue_payments():
pe.append(
"references",
{
@@ -2994,21 +3016,23 @@ def get_payment_entry(
"reference_name": overdue_payment.sales_invoice,
"payment_term": overdue_payment.payment_term,
"due_date": overdue_payment.due_date,
"total_amount": overdue_payment.outstanding,
"outstanding_amount": overdue_payment.outstanding,
"allocated_amount": overdue_payment.outstanding,
"total_amount": outstanding,
"outstanding_amount": outstanding,
"allocated_amount": outstanding,
},
)
pe.append(
"deductions",
{
"account": doc.income_account,
"cost_center": doc.cost_center,
"amount": -1 * doc.dunning_amount,
"description": _("Interest and/or dunning fee"),
},
)
if (unpaid_dunning_amount := doc.get_unpaid_base_dunning_amount()) > 0:
pe.append(
"deductions",
{
"account": doc.income_account,
"cost_center": doc.cost_center,
"amount": -1 * unpaid_dunning_amount,
"description": _("Interest and/or dunning fee"),
"dunning": doc.name,
},
)
else:
pe.append(
"references",
@@ -3290,8 +3314,10 @@ def set_grand_total_and_outstanding_amount(party_amount, dt, party_account_curre
grand_total = doc.rounded_total or doc.grand_total
outstanding_amount = doc.outstanding_amount
elif dt == "Dunning":
grand_total = doc.grand_total
outstanding_amount = doc.grand_total
# only what is left to collect, the totals on the dunning are the ones it was raised with
grand_total = sum(outstanding for _row, outstanding in doc.get_unpaid_overdue_payments())
grand_total += doc.get_unpaid_dunning_amount()
outstanding_amount = grand_total
else:
if party_account_currency == doc.company_currency:
grand_total = flt(doc.get("base_rounded_total") or doc.get("base_grand_total"))
@@ -3316,13 +3342,11 @@ def set_paid_amount_and_received_amount(
company_currency = frappe.get_cached_value("Company", doc.get("company"), "default_currency")
if bank and company_currency != bank.account_currency:
# doc currency can be different from bank currency
posting_date = doc.get("posting_date") or doc.get("transaction_date")
conversion_rate = get_exchange_rate(
bank.account_currency, party_account_currency, posting_date
)
conversion_rate = get_exchange_rate(bank.account_currency, party_account_currency)
received_amount = paid_amount / conversion_rate
else:
received_amount = paid_amount * doc.get("conversion_rate", 1)
conversion_rate = get_exchange_rate(doc.get("currency", company_currency), company_currency)
received_amount = paid_amount * conversion_rate
# if payment type is pay, then paid amount and received amount are swapped
if payment_type == "Pay":

View File

@@ -733,6 +733,23 @@ class TestPaymentEntry(FrappeTestCase):
self.validate_gl_entries(pe.name, expected_gle)
def test_internal_transfer_rejects_same_account(self):
pe = frappe.new_doc("Payment Entry")
pe.payment_type = "Internal Transfer"
pe.company = "_Test Company"
pe.paid_from = "_Test Bank - _TC"
pe.paid_to = "_Test Bank - _TC"
pe.paid_amount = 100
pe.received_amount = 100
pe.reference_no = "same-account-transfer"
pe.reference_date = nowdate()
self.assertRaisesRegex(
frappe.ValidationError,
"Paid From and Paid To accounts must be different",
pe.insert,
)
def test_payment_against_negative_sales_invoice(self):
si1 = create_sales_invoice()
@@ -1046,14 +1063,17 @@ class TestPaymentEntry(FrappeTestCase):
gle.credit_in_account_currency,
gle.debit_in_transaction_currency,
gle.credit_in_transaction_currency,
gle.transaction_currency,
gle.transaction_exchange_rate,
)
.orderby(gle.account)
.where(gle.voucher_no == payment_entry.name)
.run()
)
# transaction currency/rate come from the paid-from USD account (company currency is INR)
expected_gl_entries = (
(paid_from, 0.0, 8440.0, 0.0, 100.0, 0.0, 100.0),
("_Test Payable USD - _TC", 8440.0, 0.0, 100.0, 0.0, 100.0, 0.0),
(paid_from, 0.0, 8440.0, 0.0, 100.0, 0.0, 100.0, "USD", 84.4),
("_Test Payable USD - _TC", 8440.0, 0.0, 100.0, 0.0, 100.0, 0.0, "USD", 84.4),
)
self.assertEqual(gl_entries, expected_gl_entries)

View File

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

View File

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

View File

@@ -83,6 +83,7 @@ def get_supplier_query(doctype, txt, searchfield, start, page_len, filters):
@frappe.whitelist()
def make_payment_records(name, supplier, mode_of_payment=None):
doc = frappe.get_doc("Payment Order", name)
doc.check_permission()
make_journal_entry(doc, supplier, mode_of_payment)

View File

@@ -2436,6 +2436,86 @@ class TestPaymentReconciliation(FrappeTestCase):
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.customer3

View File

@@ -33,6 +33,8 @@ frappe.ui.form.on("Payment Request", "onload", function (frm, dt, dn) {
});
frappe.ui.form.on("Payment Request", "refresh", function (frm) {
let sending_email = false;
if (
frm.doc.payment_request_type == "Inward" &&
frm.doc.payment_channel !== "Phone" &&
@@ -41,16 +43,16 @@ frappe.ui.form.on("Payment Request", "refresh", function (frm) {
frm.doc.docstatus == 1
) {
frm.add_custom_button(__("Resend Payment Email"), function () {
frappe.call({
method: "erpnext.accounts.doctype.payment_request.payment_request.resend_payment_email",
args: { docname: frm.doc.name },
freeze: true,
freeze_message: __("Sending"),
callback: function (r) {
if (!r.exc) {
frappe.msgprint(__("Message Sent"));
}
},
if (sending_email) {
frappe.show_alert({ message: __("Sending Email"), indicator: "blue" });
return;
}
sending_email = true;
frappe.show_alert({ message: __("Sending Email"), indicator: "blue" });
frm.call("resend_payment_email").then((r) => {
const msg = !r.exc ? __("Email Sent") : __("Email couldn't be sent.");
frappe.show_alert({ message: msg, indicator: !r.exc ? "green" : "red" });
sending_email = false;
});
});
}

View File

@@ -411,6 +411,18 @@ class PaymentRequest(Document):
return payment_entry
@frappe.whitelist(methods=["POST"])
def resend_payment_email(self):
if not (
self.docstatus == 1
and self.payment_request_type == "Inward"
and self.payment_channel != "Phone"
and self.status not in ["Initiated", "Paid"]
):
frappe.throw(_("Payment Link couldn't be sent."))
self.send_email()
def send_email(self):
"""send email with payment link"""
email_args = {
@@ -428,7 +440,17 @@ class PaymentRequest(Document):
)
],
}
enqueue(method=frappe.sendmail, queue="short", timeout=300, is_async=True, **email_args)
job_id = f"send_payment_email::{self.name}"
enqueue(
method=frappe.sendmail,
queue="short",
timeout=300,
is_async=True,
job_id=job_id,
deduplicate=True,
enqueue_after_commit=True,
**email_args,
)
def get_message(self):
"""return message with payment gateway link"""
@@ -439,7 +461,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
@@ -827,11 +849,6 @@ def get_print_format_list(ref_doctype):
return {"print_format": print_format_list}
@frappe.whitelist()
def resend_payment_email(docname):
return frappe.get_doc("Payment Request", docname).send_email()
@frappe.whitelist()
def make_payment_entry(docname):
doc = frappe.get_doc("Payment Request", docname)

View File

@@ -15,6 +15,7 @@ from erpnext.accounts.doctype.account_closing_balance.account_closing_balance im
from erpnext.accounts.doctype.accounting_dimension.accounting_dimension import (
get_accounting_dimensions,
)
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
@@ -46,6 +47,14 @@ class PeriodClosingVoucher(AccountsController):
self.block_if_future_closing_voucher_exists()
self.check_closing_account_type()
self.check_closing_account_currency()
self.validate_accounts_not_frozen()
def validate_accounts_not_frozen(self, for_cancellation=False):
posting_date = self.period_end_date
if for_cancellation and is_immutable_ledger_enabled():
posting_date = getdate()
check_freezing_date(posting_date)
def validate_start_and_end_date(self):
self.fy_start_date, self.fy_end_date = frappe.db.get_value(
@@ -147,6 +156,7 @@ class PeriodClosingVoucher(AccountsController):
"Process Period Closing Voucher",
)
self.block_if_future_closing_voucher_exists()
self.validate_accounts_not_frozen(for_cancellation=True)
if not frappe.get_single_value("Accounts Settings", "use_legacy_controller_for_pcv"):
self.cancel_process_pcv_docs()

View File

@@ -499,6 +499,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",
@@ -1571,7 +1572,7 @@
"icon": "fa fa-file-text",
"is_submittable": 1,
"links": [],
"modified": "2026-02-22 04:18:50.691218",
"modified": "2026-08-12 12:00:00.000000",
"modified_by": "Administrator",
"module": "Accounts",
"name": "POS Invoice",

View File

@@ -271,40 +271,40 @@ def pos_profile_query(doctype, txt, searchfield, start, page_len, filters):
user = frappe.session["user"]
company = filters.get("company") or frappe.defaults.get_user_default("company")
args = {
"user": user,
"start": start,
"company": company,
"page_len": page_len,
"txt": "%%%s%%" % txt,
}
allowed_pos_profiles = frappe.get_list("POS Profile", pluck="name")
pos_profile = frappe.db.sql(
"""select pf.name
from
`tabPOS Profile` pf, `tabPOS Profile User` pfu
where
pfu.parent = pf.name and pfu.user = %(user)s and pf.company = %(company)s
and (pf.name like %(txt)s)
and pf.disabled = 0 limit %(page_len)s offset %(start)s""",
args,
if not allowed_pos_profiles:
return {}
pf = frappe.qb.DocType("POS Profile")
pfu = frappe.qb.DocType("POS Profile User")
pos_profile = (
frappe.qb.from_(pf)
.inner_join(pfu)
.on(pfu.parent == pf.name)
.select(pf.name)
.where((pfu.user == user) & (pf.company == company) & pf.name.like(f"%{txt}%") & (pf.disabled == 0))
.where(pf.name.isin(allowed_pos_profiles))
.limit(page_len)
.offset(start)
.run()
)
if not pos_profile:
del args["user"]
pos_profile = frappe.db.sql(
"""select pf.name
from
`tabPOS Profile` pf left join `tabPOS Profile User` pfu
on
pf.name = pfu.parent
where
ifnull(pfu.user, '') = ''
and pf.company = %(company)s
and pf.name like %(txt)s
and pf.disabled = 0""",
args,
pos_profile = (
frappe.qb.from_(pf)
.left_join(pfu)
.on(pf.name == pfu.parent)
.select(pf.name)
.where(
(pfu.user.isnull() | (pfu.user == ""))
& (pf.company == company)
& pf.name.like(f"%{txt}%")
& (pf.disabled == 0)
& (pf.name.isin(allowed_pos_profiles))
)
.run()
)
return pos_profile

View File

@@ -12,20 +12,22 @@
{
"fieldname": "fieldname",
"fieldtype": "Data",
"hidden": 1,
"label": "Fieldname"
"in_list_view": 1,
"label": "Fieldname",
"read_only": 1
},
{
"fieldname": "field",
"fieldtype": "Select",
"in_list_view": 1,
"label": "Field"
"label": "Field",
"reqd": 1
}
],
"index_web_pages_for_search": 1,
"istable": 1,
"links": [],
"modified": "2021-04-21 11:12:54.632093",
"modified": "2026-08-31 20:41:12.000000",
"modified_by": "Administrator",
"module": "Accounts",
"name": "POS Search Fields",
@@ -34,4 +36,4 @@
"sort_field": "modified",
"sort_order": "DESC",
"track_changes": 1
}
}

View File

@@ -1,40 +1,9 @@
// Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
let search_fields_datatypes = [
"Data",
"Link",
"Dynamic Link",
"Long Text",
"Select",
"Small Text",
"Text",
"Text Editor",
];
let do_not_include_fields = [
"naming_series",
"item_code",
"item_name",
"stock_uom",
"asset_naming_series",
"default_material_request_type",
"valuation_method",
"warranty_period",
"weight_uom",
"batch_number_series",
"serial_no_series",
"purchase_uom",
"customs_tariff_number",
"sales_uom",
"deferred_revenue_account",
"deferred_expense_account",
"quality_inspection_template",
"route",
"slideshow",
"website_image_alt",
"thumbnail",
"web_long_description",
];
function is_valid_invoice_field(df) {
return frappe.model.no_value_type.indexOf(df.fieldtype) === -1 || df.fieldtype === "Button";
}
frappe.ui.form.on("POS Settings", {
onload: function (frm) {
@@ -44,57 +13,46 @@ frappe.ui.form.on("POS Settings", {
get_invoice_fields: function (frm) {
frappe.model.with_doctype("POS Invoice", () => {
var fields = $.map(frappe.get_doc("DocType", "POS Invoice").fields, function (d) {
if (
frappe.model.no_value_type.indexOf(d.fieldtype) === -1 ||
["Button"].includes(d.fieldtype)
) {
return { label: d.label + " (" + d.fieldtype + ")", value: d.fieldname };
} else {
return null;
}
});
const fields = frappe.get_doc("DocType", "POS Invoice").fields.filter(is_valid_invoice_field);
frm.fields_dict.invoice_fields.grid.update_docfield_property(
"fieldname",
"options",
[""].concat(fields)
[""].concat(
fields.map((df) => {
return { label: `${df.label} (${df.fieldtype})`, value: df.fieldname };
})
)
);
});
},
add_search_options: function (frm) {
frappe.model.with_doctype("Item", () => {
var fields = $.map(frappe.get_doc("DocType", "Item").fields, function (d) {
if (
search_fields_datatypes.includes(d.fieldtype) &&
!do_not_include_fields.includes(d.fieldname)
) {
return [d.label];
} else {
return null;
}
});
frappe.call({
method: "erpnext.accounts.doctype.pos_settings.pos_settings.get_pos_search_field_options",
callback: ({ message }) => {
const fields = message || [];
fields.unshift("");
frm.fields_dict.pos_search_fields.grid.update_docfield_property("field", "options", fields);
frm.searchable_item_fields = Object.fromEntries(
fields.map((df) => [df.option, df.fieldname])
);
frm.fields_dict.pos_search_fields.grid.update_docfield_property(
"field",
"options",
[""].concat(fields.map((df) => df.option))
);
},
});
},
});
frappe.ui.form.on("POS Search Fields", {
field: function (frm, doctype, name) {
var doc = frappe.get_doc(doctype, name);
var df = $.map(frappe.get_doc("DocType", "Item").fields, function (d) {
if (doc.field == d.label && search_fields_datatypes.includes(d.fieldtype)) {
return d;
} else {
return null;
}
})[0];
const doc = frappe.get_doc(doctype, name);
doc.fieldname = df.fieldname;
frm.refresh_field("fields");
doc.fieldname = frm.searchable_item_fields?.[doc.field] || "";
frm.refresh_field("pos_search_fields");
},
});
@@ -110,6 +68,6 @@ frappe.ui.form.on("POS Field", {
doc.options = df.options;
doc.fieldtype = df.fieldtype;
doc.default_value = df.default;
frm.refresh_field("fields");
frm.refresh_field("invoice_fields");
},
});

View File

@@ -1,9 +1,50 @@
# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from collections import Counter
import frappe
from frappe import _
from frappe.model import no_value_fields
from frappe.model.document import Document
SEARCH_FIELD_TYPES = (
"Data",
"Link",
"Dynamic Link",
"Long Text",
"Select",
"Small Text",
"Text",
"Text Editor",
)
# Item fields that are of a searchable fieldtype, but are not meaningful to search a POS item by
DO_NOT_INCLUDE_FIELDS = (
"naming_series",
"item_code",
"item_name",
"stock_uom",
"asset_naming_series",
"default_material_request_type",
"valuation_method",
"warranty_period",
"weight_uom",
"batch_number_series",
"serial_no_series",
"purchase_uom",
"customs_tariff_number",
"sales_uom",
"deferred_revenue_account",
"deferred_expense_account",
"quality_inspection_template",
"route",
"slideshow",
"website_image_alt",
"thumbnail",
"web_long_description",
)
class POSSettings(Document):
# begin: auto-generated types
@@ -22,4 +63,95 @@ class POSSettings(Document):
# end: auto-generated types
def validate(self):
pass
self.validate_duplicate_invoice_fields()
self.validate_invoice_fields()
self.validate_duplicate_pos_search_fields()
self.validate_pos_search_fields()
def validate_duplicate_invoice_fields(self):
fieldnames = [field.fieldname for field in self.invoice_fields]
for fieldname, count in Counter(fieldnames).items():
if count > 1:
frappe.throw(
title=_("Duplicate POS Fields"), msg=_("'{0}' has been already added.").format(fieldname)
)
def validate_invoice_fields(self):
# the POS screen only ever creates a POS Invoice
meta = frappe.get_meta("POS Invoice")
for field in self.invoice_fields:
df = meta.get_field(field.fieldname)
if not df or not is_valid_invoice_field(df):
frappe.throw(
title=_("Invalid POS Field"),
msg=_("Row #{0}: '{1}' is not a valid field of {2}.").format(
field.idx, frappe.bold(field.fieldname or ""), frappe.bold(_("POS Invoice"))
),
)
# read only in the form, so keep them in sync with the invoice
field.label = df.label
field.fieldtype = df.fieldtype
field.options = df.options
def validate_duplicate_pos_search_fields(self):
fieldnames = [field.fieldname for field in self.pos_search_fields]
for fieldname, count in Counter(fieldnames).items():
if count > 1:
frappe.throw(
title=_("Duplicate POS Search Fields"),
msg=_("'{0}' has been already added.").format(fieldname),
)
def validate_pos_search_fields(self):
searchable_fields = {df.fieldname: df for df in get_searchable_item_fields()}
for field in self.pos_search_fields:
df = searchable_fields.get(field.fieldname)
if not df:
frappe.throw(
title=_("Invalid POS Search Field"),
msg=_("Row #{0}: '{1}' cannot be used to search items.").format(
field.idx, frappe.bold(field.fieldname or "")
),
)
if field.field != get_search_field_option(df):
frappe.throw(
title=_("Invalid POS Search Field"),
msg=_("Row #{0}: '{1}' does not match {2}.").format(
field.idx, frappe.bold(field.field or ""), frappe.bold(df.fieldname)
),
)
def is_valid_invoice_field(df):
return df.fieldtype not in no_value_fields or df.fieldtype == "Button"
def get_searchable_item_fields():
return [
df
for df in frappe.get_meta("Item").fields
if df.fieldtype in SEARCH_FIELD_TYPES and df.fieldname not in DO_NOT_INCLUDE_FIELDS
]
def get_search_field_option(df):
# the fieldname keeps the option unique, two Item fields can share a label
return f"{df.label} ({df.fieldname})"
@frappe.whitelist()
def get_pos_search_field_options():
frappe.has_permission("POS Settings", throw=True)
return [
{"option": get_search_field_option(df), "fieldname": df.fieldname}
for df in get_searchable_item_fields()
]

View File

@@ -3,6 +3,119 @@
import unittest
import frappe
from erpnext.patches.v16_0.append_fieldname_to_pos_search_fields import execute as append_fieldname
class TestPOSSettings(unittest.TestCase):
pass
def setUp(self):
self.settings = frappe.get_single("POS Settings")
self.settings.invoice_fields = []
self.settings.pos_search_fields = []
def tearDown(self):
frappe.db.rollback()
def assertInvalid(self, message):
with self.assertRaises(frappe.ValidationError) as context:
self.settings.save()
self.assertIn(message, str(context.exception))
def test_duplicate_invoice_field_is_not_allowed(self):
self.settings.append("invoice_fields", {"fieldname": "customer"})
self.settings.append("invoice_fields", {"fieldname": "customer"})
self.assertInvalid("'customer' has been already added.")
def test_unknown_invoice_field_is_not_allowed(self):
self.settings.append("invoice_fields", {"fieldname": "not_a_field"})
self.assertInvalid("is not a valid field of")
def test_layout_invoice_field_is_not_allowed(self):
self.settings.append("invoice_fields", {"fieldname": "accounting_dimensions_section"})
self.assertInvalid("is not a valid field of")
def test_invoice_field_properties_are_set_from_the_invoice(self):
self.settings.append(
"invoice_fields", {"fieldname": "customer", "label": "Tampered", "fieldtype": "Data"}
)
self.settings.save()
field = self.settings.invoice_fields[0]
self.assertEqual(field.label, "Customer")
self.assertEqual(field.fieldtype, "Link")
self.assertEqual(field.options, "Customer")
def test_searchable_item_field_is_allowed(self):
self.settings.append(
"pos_search_fields", {"field": "Description (description)", "fieldname": "description"}
)
self.settings.save()
self.assertEqual(self.settings.pos_search_fields[0].fieldname, "description")
def test_excluded_search_field_is_not_allowed(self):
self.settings.append(
"pos_search_fields", {"field": "Item Name (item_name)", "fieldname": "item_name"}
)
self.assertInvalid("cannot be used to search items")
def test_search_field_of_unsearchable_type_is_not_allowed(self):
# maintain stock is a Check field
self.settings.append(
"pos_search_fields", {"field": "Maintain Stock (is_stock_item)", "fieldname": "is_stock_item"}
)
self.assertInvalid("cannot be used to search items")
def test_unknown_search_field_is_not_allowed(self):
self.settings.append(
"pos_search_fields", {"field": "Nope (not_an_item_field)", "fieldname": "not_an_item_field"}
)
self.assertInvalid("cannot be used to search items")
def test_search_field_without_a_fieldname_is_not_allowed(self):
# the form fills the fieldname in, it cannot be picked on its own
self.settings.append("pos_search_fields", {"field": "Description (description)"})
self.assertInvalid("cannot be used to search items")
def test_search_field_option_must_match_its_fieldname(self):
self.settings.append("pos_search_fields", {"field": "Brand (brand)", "fieldname": "description"})
self.assertInvalid("does not match")
def test_bare_label_is_not_accepted_as_a_search_field(self):
# the stored option carries the fieldname, the patch backfills older rows
self.settings.append("pos_search_fields", {"field": "Description", "fieldname": "description"})
self.assertInvalid("does not match")
def test_duplicate_search_fields_are_not_allowed(self):
for _ in range(2):
self.settings.append(
"pos_search_fields", {"field": "Description (description)", "fieldname": "description"}
)
self.assertInvalid("has been already added")
def test_patch_appends_the_fieldname_to_a_legacy_search_field(self):
self.settings.append(
"pos_search_fields", {"field": "Description (description)", "fieldname": "description"}
)
self.settings.save()
row = self.settings.pos_search_fields[0].name
frappe.db.set_value("POS Search Fields", row, "field", "Description", update_modified=False)
append_fieldname()
self.assertEqual(frappe.db.get_value("POS Search Fields", row, "field"), "Description (description)")
def test_patch_leaves_an_already_migrated_search_field_alone(self):
self.settings.append(
"pos_search_fields", {"field": "Description (description)", "fieldname": "description"}
)
self.settings.save()
append_fieldname()
row = self.settings.pos_search_fields[0].name
self.assertEqual(frappe.db.get_value("POS Search Fields", row, "field"), "Description (description)")

View File

@@ -139,6 +139,8 @@ def start_pcv_processing(docname: str):
@frappe.whitelist()
def pause_pcv_processing(docname: str):
frappe.has_permission("Process Period Closing Voucher", ptype="write", doc=docname, throw=True)
ppcv = qb.DocType("Process Period Closing Voucher")
qb.update(ppcv).set(ppcv.status, "Paused").where(ppcv.name.eq(docname)).run()
@@ -154,6 +156,8 @@ def pause_pcv_processing(docname: str):
@frappe.whitelist()
def cancel_pcv_processing(docname: str):
frappe.has_permission("Process Period Closing Voucher", ptype="cancel", doc=docname, throw=True)
ppcv = qb.DocType("Process Period Closing Voucher")
qb.update(ppcv).set(ppcv.status, "Cancelled").where(ppcv.name.eq(docname)).run()
@@ -168,6 +172,8 @@ def cancel_pcv_processing(docname: str):
@frappe.whitelist()
def resume_pcv_processing(docname: str):
frappe.has_permission("Process Period Closing Voucher", ptype="write", doc=docname, throw=True)
ppcv = qb.DocType("Process Period Closing Voucher")
qb.update(ppcv).set(ppcv.status, "Running").where(ppcv.name.eq(docname)).run()

View File

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

View File

@@ -352,6 +352,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"
@@ -501,6 +502,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",
@@ -1662,7 +1664,7 @@
"idx": 204,
"is_submittable": 1,
"links": [],
"modified": "2026-07-12 23:54:21.263951",
"modified": "2026-08-12 12:00:00.000000",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Purchase Invoice",

View File

@@ -8,7 +8,7 @@ import frappe
from frappe import _, qb, throw
from frappe.model.mapper import get_mapped_doc
from frappe.query_builder.functions import Sum
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
@@ -40,6 +40,7 @@ from erpnext.assets.doctype.asset_category.asset_category import get_asset_categ
from erpnext.buying.utils import check_on_hold_or_closed_status
from erpnext.controllers.accounts_controller import merge_taxes, validate_account_head
from erpnext.controllers.buying_controller import BuyingController
from erpnext.controllers.mapper import get_qty_already_mapped
from erpnext.stock import get_warehouse_account_map
from erpnext.stock.doctype.purchase_receipt.purchase_receipt import (
get_item_account_wise_additional_cost,
@@ -291,6 +292,7 @@ class PurchaseInvoice(BuyingController):
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
)
@@ -299,6 +301,9 @@ class PurchaseInvoice(BuyingController):
self.reset_default_field_value("set_from_warehouse", "items", "from_warehouse")
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
@@ -310,6 +315,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"))
@@ -386,6 +439,9 @@ class PurchaseInvoice(BuyingController):
self.party_account_currency = account.account_currency
def check_on_hold_or_closed_status(self):
if self.get("is_return"):
return
check_list = []
for d in self.get("items"):
@@ -1365,7 +1421,20 @@ class PurchaseInvoice(BuyingController):
)
if flt(stock_amount, net_amt_precision) != flt(warehouse_debit_amount, net_amt_precision):
cost_of_goods_sold_account = self.get_company_default("default_expense_account")
stock_asset_rbnb = (
self.get_company_default("asset_received_but_not_billed", ignore_validation=True)
if item.is_fixed_asset
else self.get_company_default("stock_received_but_not_billed", ignore_validation=True)
)
fallback_account = (
(item.expense_account or stock_asset_rbnb)
if self.is_return
else (stock_asset_rbnb or item.expense_account)
)
cost_of_goods_sold_account = (
self.get_company_default("default_expense_account", ignore_validation=True)
or fallback_account
)
stock_adjustment_amt = stock_amount - warehouse_debit_amount
gl_entries.append(
@@ -1390,7 +1459,20 @@ class PurchaseInvoice(BuyingController):
and warehouse_debit_amount
!= flt(voucher_wise_stock_value.get((item.name, item.warehouse)), net_amt_precision)
):
cost_of_goods_sold_account = self.get_company_default("default_expense_account")
stock_asset_rbnb = (
self.get_company_default("asset_received_but_not_billed", ignore_validation=True)
if item.is_fixed_asset
else self.get_company_default("stock_received_but_not_billed", ignore_validation=True)
)
fallback_account = (
(item.expense_account or stock_asset_rbnb)
if self.is_return
else (stock_asset_rbnb or item.expense_account)
)
cost_of_goods_sold_account = (
self.get_company_default("default_expense_account", ignore_validation=True)
or fallback_account
)
stock_amount = flt(voucher_wise_stock_value.get((item.name, item.warehouse)), net_amt_precision)
stock_adjustment_amt = warehouse_debit_amount - stock_amount
@@ -1855,14 +1937,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_tax_withholding(self):
self.set("advance_tax", [])
@@ -2082,28 +2188,6 @@ def make_stock_entry(source_name, target_doc=None):
return doc
@frappe.whitelist()
def change_release_date(name, release_date=None):
if frappe.db.exists("Purchase Invoice", name):
pi = frappe.get_doc("Purchase Invoice", name)
pi.check_permission()
pi.db_set("release_date", release_date)
@frappe.whitelist()
def unblock_invoice(name):
if frappe.db.exists("Purchase Invoice", name):
pi = frappe.get_doc("Purchase Invoice", name)
pi.unblock_invoice()
@frappe.whitelist()
def block_invoice(name, release_date, hold_comment=None):
if frappe.db.exists("Purchase Invoice", name):
pi = frappe.get_doc("Purchase Invoice", name)
pi.block_invoice(hold_comment, release_date)
@frappe.whitelist()
def make_inter_company_sales_invoice(source_name, target_doc=None):
from erpnext.accounts.doctype.sales_invoice.sales_invoice import make_inter_company_transaction
@@ -2118,6 +2202,11 @@ def make_purchase_receipt(source_name, target_doc=None, args=None):
if isinstance(args, str):
args = json.loads(args)
mapped_qty_by_item = get_qty_already_mapped(target_doc, "purchase_invoice_item")
def received_and_mapped_qty(obj):
return flt(obj.received_qty) + flt(mapped_qty_by_item.get(obj.name, 0))
def post_parent_process(source_parent, target_parent):
remove_items_with_zero_qty(target_parent)
set_missing_values(source_parent, target_parent)
@@ -2132,13 +2221,13 @@ def make_purchase_receipt(source_name, target_doc=None, args=None):
target_parent.run_method("calculate_taxes_and_totals")
def update_item(obj, target, source_parent):
target.qty = flt(obj.qty) - flt(obj.received_qty)
target.received_qty = flt(obj.qty) - flt(obj.received_qty)
target.stock_qty = (flt(obj.qty) - flt(obj.received_qty)) * flt(obj.conversion_factor)
target.amount = (flt(obj.qty) - flt(obj.received_qty)) * flt(obj.rate)
target.base_amount = (
(flt(obj.qty) - flt(obj.received_qty)) * flt(obj.rate) * flt(source_parent.conversion_rate)
)
pending_qty = flt(obj.qty) - received_and_mapped_qty(obj)
target.qty = pending_qty
target.received_qty = pending_qty
target.stock_qty = pending_qty * flt(obj.conversion_factor)
target.amount = pending_qty * flt(obj.rate)
target.base_amount = pending_qty * flt(obj.rate) * flt(source_parent.conversion_rate)
def select_item(d):
filtered_items = args.get("filtered_children", [])
@@ -2168,7 +2257,8 @@ def make_purchase_receipt(source_name, target_doc=None, args=None):
"wip_composite_asset": "wip_composite_asset",
},
"postprocess": update_item,
"condition": lambda doc: abs(doc.received_qty) < abs(doc.qty) and select_item(doc),
"condition": lambda doc: abs(received_and_mapped_qty(doc)) < abs(doc.qty)
and select_item(doc),
},
"Purchase Taxes and Charges": {
"doctype": "Purchase Taxes and Charges",

View File

@@ -287,14 +287,166 @@ class TestPurchaseInvoice(FrappeTestCase, 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",
@@ -361,6 +513,12 @@ class TestPurchaseInvoice(FrappeTestCase, 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",
@@ -372,25 +530,15 @@ class TestPurchaseInvoice(FrappeTestCase, 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):
@@ -398,11 +546,21 @@ class TestPurchaseInvoice(FrappeTestCase, 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"
pr.conversion_rate = (70,)
pr.conversion_rate = 80
pr.supplier = "_Test Supplier USD"
pr.append(
"items",
@@ -412,34 +570,20 @@ class TestPurchaseInvoice(FrappeTestCase, 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 = 80
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}, "debit"
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(discrepancy_caused_by_exchange_rate_diff, amount)
def test_purchase_invoice_change_naming_series(self):
pi = frappe.copy_doc(test_records[1])
pi.insert()
@@ -1510,6 +1654,96 @@ class TestPurchaseInvoice(FrappeTestCase, StockTestMixin):
)
frappe.db.set_value("Company", "_Test Company", "exchange_gain_loss_account", original_account)
def test_stock_adjustment_account_fallbacks_when_default_expense_account_unset(self):
from erpnext.accounts.doctype.purchase_invoice.purchase_invoice import PurchaseInvoice
class StockAdjustmentInvoice:
company = "_Test Company"
conversion_rate = 1
update_stock = 1
is_internal_supplier = 0
return_against = None
project = None
def __init__(self, is_return, defaults):
self.is_return = is_return
self.defaults = defaults
def get(self, fieldname):
return None
def get_company_default(self, fieldname, ignore_validation=False):
return self.defaults.get(fieldname)
def get_gl_dict(self, args, *unused_args, **unused_kwargs):
return frappe._dict(args)
def make_invoice(is_return, defaults):
return StockAdjustmentInvoice(is_return, defaults)
def make_item(is_fixed_asset=0, expense_account="Item Expense - _TC"):
return frappe._dict(
{
"name": "row-1",
"warehouse": "Stores - _TC",
"valuation_rate": 10,
"qty": 10,
"conversion_factor": 1,
"base_net_amount": 100,
"item_tax_amount": 0,
"landed_cost_voucher_amount": 0,
"sales_incoming_rate": 0,
"is_fixed_asset": is_fixed_asset,
"expense_account": expense_account,
"cost_center": "Main - _TC",
"project": None,
"precision": lambda fieldname: 2,
}
)
defaults = {
"default_expense_account": None,
"stock_received_but_not_billed": "Stock Received But Not Billed - _TC",
"asset_received_but_not_billed": "Asset Received But Not Billed - _TC",
}
test_cases = (
(
"company default expense",
0,
make_item(),
{**defaults, "default_expense_account": "Default Expense - _TC"},
"Default Expense - _TC",
),
("stock rbnb", 0, make_item(), defaults, "Stock Received But Not Billed - _TC"),
(
"asset rbnb",
0,
make_item(is_fixed_asset=1),
defaults,
"Asset Received But Not Billed - _TC",
),
("return item expense", 1, make_item(), defaults, "Item Expense - _TC"),
(
"return without item expense",
1,
make_item(expense_account=None),
defaults,
"Stock Received But Not Billed - _TC",
),
)
for label, is_return, item, company_defaults, expected_account in test_cases:
with self.subTest(label=label):
invoice = make_invoice(is_return, company_defaults)
gl_entries = []
PurchaseInvoice.make_stock_adjustment_entry(
invoice, gl_entries, item, {(item.name, item.warehouse): 90}, "INR"
)
self.assertEqual(gl_entries[0].account, expected_account)
self.assertEqual(gl_entries[0].debit, 10)
self.assertEqual(gl_entries[0].debit_in_transaction_currency, 10)
@change_settings("Accounts Settings", {"unlink_payment_on_cancellation_of_invoice": 1})
def test_purchase_invoice_advance_taxes(self):
from erpnext.accounts.doctype.payment_entry.payment_entry import get_payment_entry
@@ -2457,6 +2691,39 @@ class TestPurchaseInvoice(FrappeTestCase, StockTestMixin):
self.assertEqual(row.serial_no, "\n".join(serial_nos[:2]))
self.assertEqual(row.rejected_serial_no, serial_nos[2])
def test_purchase_invoice_return_against_closed_purchase_order(self):
from erpnext.controllers.sales_and_purchase_return import make_return_doc
po = create_purchase_order(qty=2, rate=100)
invoices = []
for _ in range(2):
pi = make_pi_from_po(po.name)
pi.items[0].qty = 1
pi.submit()
invoices.append(pi)
make_return_doc("Purchase Invoice", invoices[0].name).submit()
po.reload()
po.update_status("Closed")
# a debit note against a closed Purchase Order should still go through,
# the same way a Sales Invoice return does against a closed Sales Order
debit_note = make_return_doc("Purchase Invoice", invoices[1].name)
debit_note.submit()
self.assertEqual(debit_note.docstatus, 1)
self.assertEqual(frappe.db.get_value("Purchase Order", po.name, "status"), "Closed")
# cancelling the debit note runs the same check on the closed order
debit_note.reload()
debit_note.cancel()
# a regular invoice against the closed order must still be blocked
blocked_pi = make_pi_from_po(po.name)
self.assertRaisesRegex(frappe.InvalidStatusError, "Closed", blocked_pi.save)
def test_make_pr_and_pi_from_po(self):
from erpnext.assets.doctype.asset.test_asset import create_asset_category
@@ -2814,6 +3081,23 @@ class TestPurchaseInvoice(FrappeTestCase, StockTestMixin):
self.assertRaises(StockOverReturnError, return_doc.save)
def test_partial_returns_ignore_received_qty_without_update_stock(self):
from erpnext.controllers.sales_and_purchase_return import make_return_doc
invoice = make_purchase_invoice(qty=10, received_qty=10)
first_return = make_return_doc(invoice.doctype, invoice.name)
first_return.items[0].qty = -4
first_return.save().submit()
self.assertEqual(first_return.items[0].received_qty, -10)
second_return = make_return_doc(invoice.doctype, invoice.name)
second_return.items[0].qty = -6
second_return.save().submit()
self.assertEqual(second_return.docstatus, 1)
def test_apply_discount_on_grand_total(self):
"""
To test if after applying discount on grand total,

View File

@@ -25,10 +25,12 @@
"project",
"section_break_9",
"account_currency",
"net_amount",
"tax_amount",
"tax_amount_after_discount_amount",
"total",
"column_break_14",
"base_net_amount",
"base_tax_amount",
"base_total",
"base_tax_amount_after_discount_amount",
@@ -213,11 +215,11 @@
"fieldtype": "Column Break"
},
{
"allow_on_submit": 1,
"fieldname": "project",
"fieldtype": "Link",
"label": "Project",
"options": "Project"
"allow_on_submit": 1,
"fieldname": "project",
"fieldtype": "Link",
"label": "Project",
"options": "Project"
},
{
"default": "0",
@@ -241,20 +243,38 @@
"fieldtype": "Check",
"label": "Is Tax Withholding Account",
"read_only": 1
},
{
"description": "Basis for tax calculation",
"fieldname": "net_amount",
"fieldtype": "Currency",
"label": "Net Amount",
"options": "currency",
"read_only": 1
},
{
"description": "Basis for tax calculation",
"fieldname": "base_net_amount",
"fieldtype": "Currency",
"label": "Net Amount (Company Currency)",
"options": "Company:company:default_currency",
"read_only": 1
}
],
"grid_page_length": 50,
"idx": 1,
"istable": 1,
"links": [],
"modified": "2025-04-15 13:14:48.936047",
"modified": "2026-05-01 00:38:29.543523",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Purchase Taxes and Charges",
"naming_rule": "Random",
"owner": "Administrator",
"permissions": [],
"row_format": "Dynamic",
"sort_field": "modified",
"sort_order": "DESC",
"states": [],
"track_changes": 1
}
}

View File

@@ -17,6 +17,7 @@ class PurchaseTaxesandCharges(Document):
account_currency: DF.Link | None
account_head: DF.Link
add_deduct_tax: DF.Literal["Add", "Deduct"]
base_net_amount: DF.Currency
base_tax_amount: DF.Currency
base_tax_amount_after_discount_amount: DF.Currency
base_total: DF.Currency
@@ -35,9 +36,11 @@ class PurchaseTaxesandCharges(Document):
included_in_print_rate: DF.Check
is_tax_withholding_account: DF.Check
item_wise_tax_detail: DF.Code | None
net_amount: DF.Currency
parent: DF.Data
parentfield: DF.Data
parenttype: DF.Data
project: DF.Link | None
rate: DF.Float
row_id: DF.Data | None
tax_amount: DF.Currency

View File

@@ -22,27 +22,50 @@ frappe.ui.form.on("Repost Accounting Ledger", {
},
refresh: function (frm) {
frm.add_custom_button(__("Show Preview"), () => {
frm.call({
method: "generate_preview",
doc: frm.doc,
freeze: true,
freeze_message: __("Generating Preview"),
callback: function (r) {
if (r && r.message) {
let content = r.message;
let opts = {
title: "Preview",
subtitle: "preview",
content: content,
print_settings: { orientation: "landscape" },
columns: [],
data: [],
};
frappe.render_grid(opts);
}
},
// the server refuses only while the job is alive, so a dead one can be restarted here
if (frm.doc.docstatus == 1 && !["Completed", "Cancelled"].includes(frm.doc.status)) {
frm.add_custom_button(__("Start Reposting"), () => {
frm.events.start_repost(frm);
});
}
if (frm.doc.docstatus != 2) {
frm.add_custom_button(__("Show Preview"), () => {
frm.events.generate_preview(frm);
});
}
},
generate_preview: function (frm) {
frm.call({
method: "generate_preview",
doc: frm.doc,
freeze: true,
freeze_message: __("Generating Preview"),
callback: function (r) {
if (r && r.message) {
let content = r.message;
let opts = {
title: "Preview",
subtitle: "preview",
content: content,
print_settings: { orientation: "landscape" },
columns: [],
data: [],
};
frappe.render_grid(opts);
}
},
});
},
start_repost: function (frm) {
frm.call({
method: "start_repost",
doc: frm.doc,
callback: function (r) {
frm.reload_doc();
},
});
},
});

View File

@@ -1,5 +1,6 @@
{
"actions": [],
"allow_bulk_edit": 1,
"creation": "2023-07-04 13:07:32.923675",
"default_view": "List",
"doctype": "DocType",
@@ -7,16 +8,24 @@
"engine": "InnoDB",
"field_order": [
"company",
"column_break_vpup",
"delete_cancelled_entries",
"column_break_vpup",
"status",
"section_break_metl",
"vouchers",
"amended_from"
"error_section",
"error_log",
"miscellaneous_section",
"amended_from",
"column_break_hrah",
"scheduled_job"
],
"fields": [
{
"fieldname": "company",
"fieldtype": "Link",
"in_list_view": 1,
"in_standard_filter": 1,
"label": "Company",
"options": "Company"
},
@@ -48,12 +57,54 @@
"fieldname": "delete_cancelled_entries",
"fieldtype": "Check",
"label": "Delete Cancelled Ledger Entries"
},
{
"fieldname": "error_section",
"fieldtype": "Section Break",
"label": "Error"
},
{
"fieldname": "error_log",
"fieldtype": "Code",
"label": "Error Log",
"no_copy": 1,
"print_hide": 1,
"read_only": 1
},
{
"fieldname": "miscellaneous_section",
"fieldtype": "Section Break",
"label": "Miscellaneous"
},
{
"fieldname": "column_break_hrah",
"fieldtype": "Column Break"
},
{
"depends_on": "eval:doc.docstatus >= 1;",
"fieldname": "status",
"fieldtype": "Select",
"in_list_view": 1,
"in_standard_filter": 1,
"label": "Status",
"no_copy": 1,
"options": "\nQueued\nIn Progress\nPartially Reposted\nCompleted\nFailed\nCancelled",
"read_only": 1
},
{
"fieldname": "scheduled_job",
"fieldtype": "Link",
"hidden": 1,
"label": "Scheduled Job",
"no_copy": 1,
"options": "RQ Job",
"read_only": 1
}
],
"index_web_pages_for_search": 1,
"is_submittable": 1,
"links": [],
"modified": "2024-06-03 17:30:37.012593",
"modified": "2026-07-28 00:56:50.290314",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Repost Accounting Ledger",
@@ -80,4 +131,4 @@
"sort_order": "DESC",
"states": [],
"track_changes": 1
}
}

View File

@@ -7,7 +7,14 @@ import frappe
from frappe import _, qb
from frappe.desk.form.linked_with import get_child_tables_of_doctypes
from frappe.model.document import Document
from frappe.utils.background_jobs import create_job_id, is_job_enqueued
from frappe.utils.data import comma_and
from frappe.utils.scheduler import is_scheduler_inactive
# a batch has to finish well within the timeout of the job reposting it
MAX_VOUCHERS_PER_REPOST = 50
HANDLED_VOUCHER_STATUSES = ("Reposted", "Skipped")
from erpnext.stock import get_warehouse_account_map
@@ -28,6 +35,11 @@ class RepostAccountingLedger(Document):
amended_from: DF.Link | None
company: DF.Link | None
delete_cancelled_entries: DF.Check
error_log: DF.Code | None
scheduled_job: DF.Link | None
status: DF.Literal[
"", "Queued", "In Progress", "Partially Reposted", "Completed", "Failed", "Cancelled"
]
vouchers: DF.Table[RepostAccountingLedgerItems]
# end: auto-generated types
@@ -37,6 +49,11 @@ class RepostAccountingLedger(Document):
def validate(self):
self.validate_vouchers()
self.validate_repost_preconditions()
def validate_repost_preconditions(self):
"""The checks a repost queued days ago could have outlived, re-run before it touches
the ledger. Vouchers cancelled since are skipped one by one while reposting."""
self.validate_for_closed_fiscal_year()
self.validate_for_deferred_accounting()
@@ -73,8 +90,52 @@ class RepostAccountingLedger(Document):
frappe.throw(_("Cannot Resubmit Ledger entries for vouchers in Closed fiscal year."))
def validate_vouchers(self):
if self.vouchers:
validate_docs_for_voucher_types([x.voucher_type for x in self.vouchers])
if not self.vouchers:
frappe.throw(_("Add atleast one voucher to repost."))
if len(self.vouchers) > MAX_VOUCHERS_PER_REPOST:
frappe.throw(
_("Cannot repost more than {0} vouchers at once. Split them into multiple documents.").format(
MAX_VOUCHERS_PER_REPOST
)
)
validate_docs_for_voucher_types([x.voucher_type for x in self.vouchers])
self.validate_no_duplicate_vouchers()
self.validate_vouchers_are_submitted()
def validate_no_duplicate_vouchers(self):
vouchers = [(x.voucher_type, x.voucher_no) for x in self.vouchers]
if len(vouchers) != len(set(vouchers)):
frappe.throw(_("Duplicate vouchers found. Remove the duplicate vouchers to continue to repost."))
def validate_vouchers_are_submitted(self):
voucher_type_wise_map = {}
for d in self.vouchers:
voucher_type_wise_map.setdefault(d.voucher_type, [])
voucher_type_wise_map[d.voucher_type].append(d.voucher_no)
non_submitted_vouchers = []
for key in voucher_type_wise_map.keys():
non_submitted_vouchers.extend(
frappe.get_all(
key,
filters={"name": ["in", voucher_type_wise_map[key]], "docstatus": ["!=", 1]},
pluck="name",
)
)
if non_submitted_vouchers:
frappe.throw(
_("The following vouchers are not submitted: {0}").format(
comma_and(non_submitted_vouchers, add_quotes=True)
)
)
def on_discard(self):
self.db_set("status", "Cancelled")
def get_existing_ledger_entries(self):
vouchers = [x.voucher_no for x in self.vouchers]
@@ -139,80 +200,245 @@ class RepostAccountingLedger(Document):
return rendered_page
def on_submit(self):
if len(self.vouchers) > 5:
job_name = "repost_accounting_ledger_" + self.name
frappe.enqueue(
method="erpnext.accounts.doctype.repost_accounting_ledger.repost_accounting_ledger.start_repost",
account_repost_doc=self.name,
is_async=True,
job_name=job_name,
enqueue_after_commit=True,
self.start_repost()
def before_cancel(self):
self._raise_error_if_reposting_in_progress()
def on_cancel(self):
self.db_set("status", "Cancelled")
def _raise_error_if_reposting_in_progress(self):
if self.scheduled_job and is_job_enqueued(_repost_job_id(self.name)):
frappe.throw(_("Reposting is still in progress in background."))
@frappe.whitelist()
def start_repost(self):
if self.docstatus != 1:
frappe.throw(_("Reposting can be started only for submitted document."))
# under a row lock, so two concurrent starts cannot both get past here
status = frappe.db.get_value(self.doctype, self.name, "status", for_update=True)
if status in ("Completed", "Cancelled"):
frappe.throw(_("Reposting cannot be started when status is {0}.").format(status))
# `Queued` and `In Progress` are held back by the job, not by the status: a worker that
# died leaves the status behind and the document has to stay restartable
self._raise_error_if_reposting_in_progress()
self.check_permission("write")
# workers pick up enqueued jobs whether or not the scheduler runs, so this is a warning
if is_scheduler_inactive():
frappe.msgprint(
_("Scheduler is inactive. Reposting will only run once background jobs are processed."),
alert=True,
indicator="orange",
)
frappe.msgprint(_("Repost has started in the background"))
else:
start_repost(self.name)
self.db_set({"status": "Queued", "scheduled_job": create_job_id(_repost_job_id(self.name))})
_enqueue_repost(self.name)
frappe.msgprint(_("Repost has started in the background"), alert=True, indicator="blue")
@frappe.whitelist()
def start_repost(account_repost_doc: str | None = None) -> None:
from erpnext.accounts.general_ledger import make_reverse_gl_entries
def _repost_job_id(repost_doc_name: str) -> str:
"""Derived from the document, so a repost can only ever have one job."""
return f"repost_accounting_ledger::{repost_doc_name}"
def _enqueue_repost(repost_doc_name: str) -> None:
"""Hand the repost to a background worker.
Tests run it in the foreground, inside their own transaction: documents edited after submit
repost themselves through `repost_accounting_entries`, and tests across apps assert on the
ledger right after doing so.
"""
frappe.enqueue(
method="erpnext.accounts.doctype.repost_accounting_ledger.repost_accounting_ledger.repost",
repost_doc_name=repost_doc_name,
commit=not frappe.flags.in_test,
queue="long",
timeout=1500,
job_id=_repost_job_id(repost_doc_name),
deduplicate=True,
enqueue_after_commit=True,
now=frappe.flags.in_test,
)
def _lock_vouchers(vouchers) -> dict:
"""Lock every voucher up front so a concurrent repost cannot touch the same GL entries.
Returns them keyed by voucher, so reposting does not load them again. These are file locks
under the site directory: they serialise nothing across hosts that do not share it, and a
worker killed outright leaves them behind until they expire.
"""
locked_docs = {}
try:
for x in vouchers:
doc = frappe.get_doc(x.voucher_type, x.voucher_no)
doc.lock()
locked_docs[(x.voucher_type, x.voucher_no)] = doc
except Exception:
for doc in locked_docs.values():
doc.unlock()
raise
return locked_docs
def repost(repost_doc_name: str, commit: bool = True):
"""Repost every voucher of the document, one transaction at a time.
`commit` says whether this call owns the transaction. The background job does, and commits
after every voucher so progress survives a crash; a caller inside its own passes `False`.
"""
from erpnext.accounts.utils import _delete_accounting_ledger_entries, _delete_adv_pl_entries
frappe.flags.through_repost_accounting_ledger = True
if account_repost_doc:
repost_doc = frappe.get_doc("Repost Accounting Ledger", account_repost_doc)
repost_doc.check_permission("write")
if repost_doc.docstatus == 1:
# Prevent repost on invoices with deferred accounting
repost_doc.validate_for_deferred_accounting()
repost_doc = frappe.get_doc("Repost Accounting Ledger", repost_doc_name)
locked_docs = {}
for x in repost_doc.vouchers:
doc = frappe.get_doc(x.voucher_type, x.voucher_no)
try:
repost_doc.validate_repost_preconditions()
# a retry leaves the vouchers it is done with alone: they are not locked, not loaded
# and not reposted again
pending = [x for x in repost_doc.vouchers if x.status not in HANDLED_VOUCHER_STATUSES]
locked_docs = _lock_vouchers(pending)
repost_doc.db_set("status", "In Progress", commit=commit)
for position, x in enumerate(pending, start=1):
frappe.publish_progress(
position * 100 / len(pending),
doctype=repost_doc.doctype,
docname=repost_doc.name,
description=_("Reposting {0} {1}").format(x.voucher_type, x.voucher_no),
)
save_point = "reposting"
frappe.db.savepoint(save_point=save_point)
try:
doc = locked_docs[(x.voucher_type, x.voucher_no)]
if doc.docstatus == 2:
x.db_set({"status": "Skipped", "traceback": ""})
continue
if repost_doc.delete_cancelled_entries:
frappe.db.delete(
"GL Entry", filters={"voucher_type": doc.doctype, "voucher_no": doc.name}
)
frappe.db.delete(
"Payment Ledger Entry", filters={"voucher_type": doc.doctype, "voucher_no": doc.name}
)
frappe.db.delete(
"Advance Payment Ledger Entry",
filters={"voucher_type": doc.doctype, "voucher_no": doc.name},
)
_delete_accounting_ledger_entries(doc.doctype, doc.name)
_delete_adv_pl_entries(doc.doctype, doc.name)
if doc.doctype in ["Sales Invoice", "Purchase Invoice"]:
if not repost_doc.delete_cancelled_entries:
doc.docstatus = 2
doc.make_gl_entries_on_cancel(from_repost=True)
_repost_vouchers(doc, repost_doc.delete_cancelled_entries)
except Exception:
frappe.db.rollback(save_point=save_point)
doc.docstatus = 1
if doc.doctype == "Sales Invoice":
doc.force_set_against_income_account()
else:
doc.force_set_against_expense_account()
doc.make_gl_entries()
x.db_set({"status": "Failed", "traceback": frappe.get_traceback()})
else:
x.db_set({"status": "Reposted", "traceback": ""})
finally:
if commit:
frappe.db.commit() # nosemgrep
elif doc.doctype == "Purchase Receipt":
if not repost_doc.delete_cancelled_entries:
doc.docstatus = 2
doc.make_gl_entries_on_cancel(from_repost=True)
except Exception:
if commit:
frappe.db.rollback()
doc.docstatus = 1
doc.make_gl_entries(from_repost=True)
_record_repost_failure(repost_doc, commit=commit)
raise
else:
repost_doc.db_set({"status": _derive_status(repost_doc), "error_log": ""}, notify=True)
finally:
for doc in locked_docs.values():
doc.unlock()
if commit:
frappe.db.commit() # nosemgrep
elif doc.doctype in ["Payment Entry", "Journal Entry", "Expense Claim"]:
if not repost_doc.delete_cancelled_entries:
doc.make_gl_entries(1)
doc.make_gl_entries()
elif doc.doctype in frappe.get_hooks("repost_allowed_doctypes"):
if hasattr(doc, "make_gl_entries") and callable(doc.make_gl_entries):
if not repost_doc.delete_cancelled_entries:
if "cancel" in inspect.getfullargspec(doc.make_gl_entries):
doc.make_gl_entries(cancel=1)
else:
make_reverse_gl_entries(voucher_type=doc.doctype, voucher_no=doc.name)
doc.make_gl_entries()
def _derive_status(repost_doc) -> str:
"""Vouchers are committed one by one, so the status follows what was actually handled."""
handled = sum(1 for voucher in repost_doc.vouchers if voucher.status in HANDLED_VOUCHER_STATUSES)
if handled == len(repost_doc.vouchers):
return "Completed"
elif handled == 0:
return "Failed"
return "Partially Reposted"
def _record_repost_failure(repost_doc, commit=False) -> None:
"""Persist the traceback of a run that could not finish, without discarding its progress."""
# the traceback with frame locals goes to the Error Log, which is permissioned separately
traceback = frappe.get_traceback()
frappe.log_error(
title=_("Unable to Repost Accounting Ledger"),
reference_doctype=repost_doc.doctype,
reference_name=repost_doc.name,
)
frappe.db.set_value(
repost_doc.doctype, repost_doc.name, {"error_log": traceback, "status": _derive_status(repost_doc)}
)
if commit:
frappe.db.commit()
def _repost_vouchers(doc, delete_cancelled_entries: bool | int | None):
if doc.doctype in ["Sales Invoice", "Purchase Invoice"]:
_repost_invoices(doc, delete_cancelled_entries)
elif doc.doctype == "Purchase Receipt":
_repost_purchase_receipt(doc, delete_cancelled_entries)
elif doc.doctype in ["Payment Entry", "Journal Entry"]:
_repost_pe_je(doc, delete_cancelled_entries)
elif doc.doctype in frappe.get_hooks("repost_allowed_doctypes"):
_repost_allowed_hook_doctypes(doc, delete_cancelled_entries)
def _repost_invoices(invoice_doc, delete_cancelled_entries):
if not delete_cancelled_entries:
invoice_doc.docstatus = 2
invoice_doc.make_gl_entries_on_cancel(from_repost=True)
invoice_doc.docstatus = 1
if invoice_doc.doctype == "Sales Invoice":
invoice_doc.force_set_against_income_account()
else:
invoice_doc.force_set_against_expense_account()
invoice_doc.make_gl_entries()
def _repost_purchase_receipt(receipt_doc, delete_cancelled_entries):
if not delete_cancelled_entries:
receipt_doc.docstatus = 2
receipt_doc.make_gl_entries_on_cancel(from_repost=True)
receipt_doc.docstatus = 1
receipt_doc.make_gl_entries(from_repost=True)
def _repost_pe_je(entry_doc, delete_cancelled_entries):
if not delete_cancelled_entries:
entry_doc.make_gl_entries(cancel=1)
entry_doc.make_gl_entries()
def _repost_allowed_hook_doctypes(repost_doc, delete_cancelled_entries: bool | int | None):
from erpnext.accounts.general_ledger import make_reverse_gl_entries
if hasattr(repost_doc, "make_gl_entries") and callable(repost_doc.make_gl_entries):
if not delete_cancelled_entries:
if "cancel" in inspect.getfullargspec(repost_doc.make_gl_entries).args:
repost_doc.make_gl_entries(cancel=1)
else:
make_reverse_gl_entries(voucher_type=repost_doc.doctype, voucher_no=repost_doc.name)
repost_doc.make_gl_entries()
def get_allowed_types_from_settings(child_doc: bool = False):
@@ -247,19 +473,24 @@ def get_child_docs(doc: list) -> list:
def validate_docs_for_deferred_accounting(sales_docs, purchase_docs):
docs_with_deferred_revenue = frappe.db.get_all(
"Sales Invoice Item",
filters={"parent": ["in", sales_docs], "docstatus": 1, "enable_deferred_revenue": True},
fields=["parent"],
as_list=1,
)
docs_with_deferred_revenue = ()
docs_with_deferred_expense = ()
docs_with_deferred_expense = frappe.db.get_all(
"Purchase Invoice Item",
filters={"parent": ["in", purchase_docs], "docstatus": 1, "enable_deferred_expense": 1},
fields=["parent"],
as_list=1,
)
if sales_docs:
docs_with_deferred_revenue = frappe.db.get_all(
"Sales Invoice Item",
filters={"parent": ["in", sales_docs], "docstatus": 1, "enable_deferred_revenue": True},
fields=["parent"],
as_list=1,
)
if purchase_docs:
docs_with_deferred_expense = frappe.db.get_all(
"Purchase Invoice Item",
filters={"parent": ["in", purchase_docs], "docstatus": 1, "enable_deferred_expense": 1},
fields=["parent"],
as_list=1,
)
if docs_with_deferred_revenue or docs_with_deferred_expense:
frappe.throw(

View File

@@ -0,0 +1,16 @@
frappe.listview_settings["Repost Accounting Ledger"] = {
add_fields: ["status"],
// drafts and cancelled documents are coloured by the framework before it gets here
get_indicator: function (doc) {
if (!doc.status) return;
const status_color = {
Queued: "yellow",
"In Progress": "blue",
"Partially Reposted": "orange",
Completed: "green",
Failed: "red",
};
return [__(doc.status), status_color[doc.status] || "gray", "status,=," + doc.status];
},
};

View File

@@ -1,20 +1,35 @@
# Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
from contextlib import contextmanager
from unittest.mock import patch
import frappe
from frappe import qb
from frappe.query_builder.functions import Sum
from frappe.tests.utils import FrappeTestCase, change_settings
from frappe.utils import add_days, nowdate, today
from erpnext.accounts.doctype.journal_entry.test_journal_entry import make_journal_entry
from erpnext.accounts.doctype.payment_entry.payment_entry import get_payment_entry
from erpnext.accounts.doctype.payment_request.payment_request import make_payment_request
from erpnext.accounts.doctype.repost_accounting_ledger.repost_accounting_ledger import (
_lock_vouchers,
_record_repost_failure,
_repost_allowed_hook_doctypes,
_repost_job_id,
_repost_vouchers,
repost,
)
from erpnext.accounts.doctype.sales_invoice.test_sales_invoice import create_sales_invoice
from erpnext.accounts.test.accounts_mixin import AccountsTestMixin
from erpnext.accounts.utils import get_fiscal_year
from erpnext.stock.doctype.item.test_item import make_item
from erpnext.stock.doctype.purchase_receipt.test_purchase_receipt import get_gl_entries, make_purchase_receipt
REPOST_MODULE = "erpnext.accounts.doctype.repost_accounting_ledger.repost_accounting_ledger"
SIMULATED_FAILURE = "Simulated repost failure"
class TestRepostAccountingLedger(AccountsTestMixin, FrappeTestCase):
def setUp(self):
@@ -26,8 +41,8 @@ class TestRepostAccountingLedger(AccountsTestMixin, FrappeTestCase):
def tearDown(self):
frappe.db.rollback()
def test_01_basic_functions(self):
si = create_sales_invoice(
def make_invoice(self, **kwargs):
return create_sales_invoice(
item=self.item,
company=self.company,
customer=self.customer,
@@ -35,8 +50,71 @@ class TestRepostAccountingLedger(AccountsTestMixin, FrappeTestCase):
parent_cost_center=self.cost_center,
cost_center=self.cost_center,
rate=100,
**kwargs,
)
def make_invoice_and_payment(self):
si = self.make_invoice()
pe = get_payment_entry(si.doctype, si.name)
pe.save().submit()
return si, pe
def create_repost_doc(self, vouchers, delete_cancelled_entries=False, submit=False):
ral = frappe.new_doc("Repost Accounting Ledger")
ral.company = self.company
ral.delete_cancelled_entries = delete_cancelled_entries
for voucher in vouchers:
ral.append("vouchers", {"voucher_type": voucher.doctype, "voucher_no": voucher.name})
ral.save()
if submit:
ral.submit()
ral.reload()
return ral
@contextmanager
def patched_repost(self, fail_for=()):
"""Yield the vouchers handed over to `_repost_vouchers`, failing the given types."""
reposted = []
def repost_voucher(doc, delete_cancelled_entries):
reposted.append(doc.name)
if doc.doctype in fail_for:
frappe.throw(SIMULATED_FAILURE)
_repost_vouchers(doc, delete_cancelled_entries)
with patch(f"{REPOST_MODULE}._repost_vouchers", new=repost_voucher):
yield reposted
def make_period_closing_voucher(self):
fy = get_fiscal_year(today(), company=self.company)
pcv = frappe.get_doc(
{
"doctype": "Period Closing Voucher",
"transaction_date": today(),
"period_start_date": fy[1],
"period_end_date": today(),
"company": self.company,
"fiscal_year": fy[0],
"cost_center": self.cost_center,
"closing_account_head": self.retained_earnings,
"remarks": "test",
}
)
return pcv.save().submit()
def get_gl_totals(self, voucher_no, is_cancelled=0):
gl = qb.DocType("GL Entry")
return (
qb.from_(gl)
.select(Sum(gl.debit).as_("debit"), Sum(gl.credit).as_("credit"))
.where((gl.voucher_no == voucher_no) & (gl.is_cancelled == is_cancelled))
.run()
)[0]
def test_01_basic_functions(self):
si = self.make_invoice()
preq = frappe.get_doc(
make_payment_request(
dt=si.doctype,
@@ -70,51 +148,24 @@ class TestRepostAccountingLedger(AccountsTestMixin, FrappeTestCase):
gle = frappe.db.get_all("GL Entry", filters={"voucher_no": si.name, "account": self.debit_to})
frappe.db.set_value("GL Entry", gle[0], "debit", 90)
gl = qb.DocType("GL Entry")
res = (
qb.from_(gl)
.select(gl.voucher_no, Sum(gl.debit).as_("debit"), Sum(gl.credit).as_("credit"))
.where((gl.voucher_no == si.name) & (gl.is_cancelled == 0))
.run()
)
# Assert incorrect ledger balance
self.assertNotEqual(res[0], (si.name, 100, 100))
self.assertNotEqual(self.get_gl_totals(si.name), (100, 100))
# Submit repost document
ral.save().submit()
res = (
qb.from_(gl)
.select(gl.voucher_no, Sum(gl.debit).as_("debit"), Sum(gl.credit).as_("credit"))
.where((gl.voucher_no == si.name) & (gl.is_cancelled == 0))
.run()
)
# Ledger should reflect correct amount post repost
self.assertEqual(res[0], (si.name, 100, 100))
self.assertEqual(self.get_gl_totals(si.name), (100, 100))
def test_02_deferred_accounting_valiations(self):
si = create_sales_invoice(
item=self.item,
company=self.company,
customer=self.customer,
debit_to=self.debit_to,
parent_cost_center=self.cost_center,
cost_center=self.cost_center,
rate=100,
do_not_submit=True,
)
si = self.make_invoice(do_not_submit=True)
si.items[0].enable_deferred_revenue = True
si.items[0].deferred_revenue_account = self.deferred_revenue
si.items[0].service_start_date = nowdate()
si.items[0].service_end_date = add_days(nowdate(), 90)
si.save().submit()
ral = frappe.new_doc("Repost Accounting Ledger")
ral.company = self.company
ral.append("vouchers", {"voucher_type": si.doctype, "voucher_no": si.name})
self.assertRaises(frappe.ValidationError, ral.save)
self.assertRaises(frappe.ValidationError, self.create_repost_doc, [si])
@change_settings("Accounts Settings", {"delete_linked_ledger_entries": 1})
def test_04_pcv_validation(self):
@@ -122,86 +173,29 @@ class TestRepostAccountingLedger(AccountsTestMixin, FrappeTestCase):
gl = frappe.qb.DocType("GL Entry")
qb.from_(gl).delete().where(gl.company == self.company).run()
si = create_sales_invoice(
item=self.item,
company=self.company,
customer=self.customer,
debit_to=self.debit_to,
parent_cost_center=self.cost_center,
cost_center=self.cost_center,
rate=100,
)
fy = get_fiscal_year(today(), company=self.company)
pcv = frappe.get_doc(
{
"doctype": "Period Closing Voucher",
"transaction_date": today(),
"period_start_date": fy[1],
"period_end_date": today(),
"company": self.company,
"fiscal_year": fy[0],
"cost_center": self.cost_center,
"closing_account_head": self.retained_earnings,
"remarks": "test",
}
)
pcv.save().submit()
si = self.make_invoice()
pcv = self.make_period_closing_voucher()
ral = frappe.new_doc("Repost Accounting Ledger")
ral.company = self.company
ral.append("vouchers", {"voucher_type": si.doctype, "voucher_no": si.name})
self.assertRaises(frappe.ValidationError, ral.save)
self.assertRaises(frappe.ValidationError, self.create_repost_doc, [si])
pcv.reload()
pcv.cancel()
pcv.delete()
def test_03_deletion_flag_and_preview_function(self):
si = create_sales_invoice(
item=self.item,
company=self.company,
customer=self.customer,
debit_to=self.debit_to,
parent_cost_center=self.cost_center,
cost_center=self.cost_center,
rate=100,
)
pe = get_payment_entry(si.doctype, si.name)
pe.save().submit()
si, pe = self.make_invoice_and_payment()
# with deletion flag set
ral = frappe.new_doc("Repost Accounting Ledger")
ral.company = self.company
ral.delete_cancelled_entries = True
ral.append("vouchers", {"voucher_type": si.doctype, "voucher_no": si.name})
ral.append("vouchers", {"voucher_type": pe.doctype, "voucher_no": pe.name})
ral.save().submit()
self.create_repost_doc([si, pe], delete_cancelled_entries=True, submit=True)
self.assertIsNone(frappe.db.exists("GL Entry", {"voucher_no": si.name, "is_cancelled": 1}))
self.assertIsNone(frappe.db.exists("GL Entry", {"voucher_no": pe.name, "is_cancelled": 1}))
def test_05_without_deletion_flag(self):
si = create_sales_invoice(
item=self.item,
company=self.company,
customer=self.customer,
debit_to=self.debit_to,
parent_cost_center=self.cost_center,
cost_center=self.cost_center,
rate=100,
)
pe = get_payment_entry(si.doctype, si.name)
pe.save().submit()
si, pe = self.make_invoice_and_payment()
# without deletion flag set
ral = frappe.new_doc("Repost Accounting Ledger")
ral.company = self.company
ral.delete_cancelled_entries = False
ral.append("vouchers", {"voucher_type": si.doctype, "voucher_no": si.name})
ral.append("vouchers", {"voucher_type": pe.doctype, "voucher_no": pe.name})
ral.save().submit()
self.create_repost_doc([si, pe], submit=True)
self.assertIsNotNone(frappe.db.exists("GL Entry", {"voucher_no": si.name, "is_cancelled": 1}))
self.assertIsNotNone(frappe.db.exists("GL Entry", {"voucher_no": pe.name, "is_cancelled": 1}))
@@ -247,11 +241,7 @@ class TestRepostAccountingLedger(AccountsTestMixin, FrappeTestCase):
another_provisional_account,
)
repost_doc = frappe.new_doc("Repost Accounting Ledger")
repost_doc.company = self.company
repost_doc.delete_cancelled_entries = True
repost_doc.append("vouchers", {"voucher_type": pr.doctype, "voucher_no": pr.name})
repost_doc.save().submit()
repost_doc = self.create_repost_doc([pr], delete_cancelled_entries=True, submit=True)
pr_gles_after_repost = get_gl_entries(pr.doctype, pr.name, skip_cancelled=True)
expected_pr_gles_after_repost = [
@@ -272,6 +262,279 @@ class TestRepostAccountingLedger(AccountsTestMixin, FrappeTestCase):
company.default_provisional_account = None
company.save()
def test_07_voucher_validations(self):
submitted_si = self.make_invoice()
draft_si = self.make_invoice(do_not_submit=True)
cancelled_si = self.make_invoice()
cancelled_si.cancel()
for vouchers, exception, message in (
([], frappe.ValidationError, "Add atleast one voucher"),
([submitted_si, submitted_si], frappe.ValidationError, "Duplicate vouchers found"),
([draft_si], frappe.ValidationError, f"not submitted.*{draft_si.name}"),
# cancelled vouchers don't make it past link validation
([cancelled_si], frappe.CancelledLinkError, "Cannot link cancelled document"),
):
with self.subTest(vouchers=[x.name for x in vouchers]):
self.assertRaisesRegex(exception, message, self.create_repost_doc, vouchers)
self.create_repost_doc([submitted_si])
def test_08_voucher_count_limit(self):
si, pe = self.make_invoice_and_payment()
another_si = self.make_invoice()
with patch(f"{REPOST_MODULE}.MAX_VOUCHERS_PER_REPOST", 2):
self.create_repost_doc([si, pe])
self.assertRaisesRegex(
frappe.ValidationError,
"Cannot repost more than 2 vouchers",
self.create_repost_doc,
[si, pe, another_si],
)
def test_09_status_lifecycle(self):
si, pe = self.make_invoice_and_payment()
ral = self.create_repost_doc([si, pe])
self.assertEqual(ral.status, "")
ral.submit()
ral.reload()
self.assertEqual(ral.status, "Completed")
self.assertFalse(ral.error_log)
for voucher in ral.vouchers:
self.assertEqual(voucher.status, "Reposted")
self.assertFalse(voucher.traceback)
ral.cancel()
ral.reload()
self.assertEqual(ral.status, "Cancelled")
# the `discard` flow (and the `on_discard` hook it triggers) only exists on v16,
# so there is nothing to assert here on v15
def test_10_start_repost_guards(self):
si = self.make_invoice()
ral = self.create_repost_doc([si])
self.assertRaisesRegex(frappe.ValidationError, "only for submitted document", ral.start_repost)
ral.submit()
ral.reload()
self.assertRaisesRegex(
frappe.ValidationError, "cannot be started when status is Completed", ral.start_repost
)
# a document left behind by a worker that died mid-repost
ral.db_set("status", "In Progress")
with patch(f"{REPOST_MODULE}.is_job_enqueued", return_value=True):
self.assertRaisesRegex(
frappe.ValidationError, "still in progress in background", ral.start_repost
)
self.assertRaisesRegex(frappe.ValidationError, "still in progress in background", ral.cancel)
# `cancel` flips docstatus in memory before running `before_cancel`
ral.reload()
with patch(f"{REPOST_MODULE}.is_job_enqueued", return_value=False):
# the job is gone, so `In Progress` must not keep the document stuck
ral.start_repost()
ral.reload()
self.assertEqual(ral.status, "Completed")
def test_11_repost_job_is_tied_to_the_document(self):
si = self.make_invoice()
ral = self.create_repost_doc([si], submit=True)
ral.db_set("status", "Failed")
with patch(f"{REPOST_MODULE}.frappe.enqueue") as enqueue:
ral.start_repost()
kwargs = enqueue.call_args.kwargs
self.assertEqual(kwargs["repost_doc_name"], ral.name)
self.assertEqual(kwargs["job_id"], _repost_job_id(ral.name))
# a second start cannot queue a second job for the same document
self.assertTrue(kwargs["deduplicate"])
def test_12_voucher_failures_are_isolated_and_retried(self):
si, pe = self.make_invoice_and_payment()
pe_gl_entries = frappe.db.count("GL Entry", {"voucher_no": pe.name})
# the deletion flag drops the existing entries before reposting them
ral = self.create_repost_doc([si, pe], delete_cancelled_entries=True)
with self.patched_repost(fail_for=["Payment Entry"]):
ral.submit()
ral.reload()
self.assertEqual(ral.status, "Partially Reposted")
si_row, pe_row = ral.vouchers
self.assertEqual((si_row.status, pe_row.status), ("Reposted", "Failed"))
self.assertFalse(si_row.traceback)
self.assertIn(SIMULATED_FAILURE, pe_row.traceback)
# the failed voucher is rolled back to its savepoint, so its entries are back
self.assertEqual(frappe.db.count("GL Entry", {"voucher_no": pe.name}), pe_gl_entries)
# a retry only picks up the vouchers that are not reposted yet, and leaves the rest
# alone entirely: they are not locked or loaded either
with (
patch(f"{REPOST_MODULE}._lock_vouchers", side_effect=_lock_vouchers) as lock_vouchers,
self.patched_repost() as retried,
):
ral.start_repost()
self.assertEqual(retried, [pe.name])
self.assertEqual([x.voucher_no for x in lock_vouchers.call_args.args[0]], [pe.name])
ral.reload()
self.assertEqual(ral.status, "Completed")
for voucher in ral.vouchers:
self.assertEqual(voucher.status, "Reposted")
self.assertFalse(voucher.traceback)
def test_13_status_of_a_run_that_could_not_finish(self):
si, pe = self.make_invoice_and_payment()
ral = self.create_repost_doc([si, pe])
with self.patched_repost(fail_for=["Payment Entry"]):
ral.submit()
ral.reload()
# the job dies after the loop committed the invoice, e.g. killed or timed out
try:
frappe.throw(SIMULATED_FAILURE)
except frappe.ValidationError:
_record_repost_failure(ral)
ral.reload()
# progress already committed must not be reported as a total failure
self.assertEqual(ral.status, "Partially Reposted")
self.assertIn(SIMULATED_FAILURE, ral.error_log)
self.assertTrue(
frappe.db.exists("Error Log", {"reference_doctype": ral.doctype, "reference_name": ral.name})
)
@change_settings("Accounts Settings", {"delete_linked_ledger_entries": 1})
def test_14_period_closed_after_the_repost_was_started(self):
gl = qb.DocType("GL Entry")
qb.from_(gl).delete().where(gl.company == self.company).run()
si = self.make_invoice()
ral = self.create_repost_doc([si], submit=True)
ral.db_set("status", "Failed")
ral.vouchers[0].db_set("status", "Pending")
# the period is closed between the repost being started and the job running
self.make_period_closing_voucher()
gl_entries = frappe.db.count("GL Entry", {"voucher_no": si.name})
self.assertRaisesRegex(frappe.ValidationError, "Closed fiscal year", repost, ral.name, commit=False)
ral.reload()
self.assertEqual(ral.status, "Failed")
self.assertIn("Closed fiscal year", ral.error_log)
# the ledger is left exactly as it was
self.assertEqual(frappe.db.count("GL Entry", {"voucher_no": si.name}), gl_entries)
self.assertEqual(ral.vouchers[0].status, "Pending")
def test_15_failed_repost_skips_cancelled_voucher(self):
si = self.make_invoice()
ral = self.create_repost_doc([si])
with self.patched_repost(fail_for=["Sales Invoice"]):
ral.submit()
ral.reload()
self.assertEqual(ral.status, "Failed")
si.reload()
si.cancel()
ral.start_repost()
ral.reload()
# nothing was reposted, but there is nothing left to repost either
self.assertEqual(ral.status, "Completed")
self.assertEqual(ral.vouchers[0].status, "Skipped")
self.assertFalse(ral.vouchers[0].traceback)
def test_16_concurrent_repost_is_blocked_by_voucher_lock(self):
si, pe = self.make_invoice_and_payment()
ral = self.create_repost_doc([si, pe])
# a concurrent repost holding the lock on the second voucher
locked_pe = frappe.get_doc(pe.doctype, pe.name)
locked_pe.lock()
try:
self.assertRaises(frappe.DocumentLockedError, ral.submit)
# vouchers locked before the failure are released again
self.assertFalse(frappe.get_doc(si.doctype, si.name).is_locked)
finally:
locked_pe.unlock()
def test_17_journal_entry_repost(self):
je = make_journal_entry("_Test Bank - _TC", "_Test Cash - _TC", 500, submit=True)
je = frappe.get_doc("Journal Entry", je.name)
self.assertEqual(self.get_gl_totals(je.name), (500.0, 500.0))
# without the deletion flag the 2 original entries are marked as cancelled,
# along with the 2 reverse entries booked against them
for delete_cancelled_entries, cancelled_entries in ((False, 4), (True, 0)):
with self.subTest(delete_cancelled_entries=delete_cancelled_entries):
ral = self.create_repost_doc(
[je], delete_cancelled_entries=delete_cancelled_entries, submit=True
)
self.assertEqual(ral.status, "Completed")
self.assertEqual(self.get_gl_totals(je.name), (500.0, 500.0))
self.assertEqual(
frappe.db.count("GL Entry", {"voucher_no": je.name, "is_cancelled": 1}),
cancelled_entries,
)
def test_18_hook_allowed_doctype_repost(self):
class VoucherWithCancelArg:
doctype = "Test Repost Voucher"
name = "TRV-00001"
def __init__(self):
self.calls = []
def make_gl_entries(self, cancel=0):
self.calls.append(cancel)
class VoucherWithoutCancelArg(VoucherWithCancelArg):
def make_gl_entries(self):
self.calls.append("repost")
# vouchers that can reverse their own entries are asked to do so first
doc = VoucherWithCancelArg()
_repost_allowed_hook_doctypes(doc, delete_cancelled_entries=False)
self.assertEqual(doc.calls, [1, 0])
# nothing to reverse when the old entries are deleted
doc = VoucherWithCancelArg()
_repost_allowed_hook_doctypes(doc, delete_cancelled_entries=True)
self.assertEqual(doc.calls, [0])
# the rest fall back to the generic reversal
doc = VoucherWithoutCancelArg()
with patch("erpnext.accounts.general_ledger.make_reverse_gl_entries") as make_reverse_gl_entries:
_repost_allowed_hook_doctypes(doc, delete_cancelled_entries=False)
make_reverse_gl_entries.assert_called_once_with(voucher_type=doc.doctype, voucher_no=doc.name)
self.assertEqual(doc.calls, ["repost"])
def update_repost_settings():
allowed_types = [

View File

@@ -1,5 +1,6 @@
{
"actions": [],
"allow_bulk_edit": 1,
"allow_rename": 1,
"creation": "2023-07-04 14:14:01.243848",
"doctype": "DocType",
@@ -7,28 +8,63 @@
"engine": "InnoDB",
"field_order": [
"voucher_type",
"voucher_no"
"column_break_ndex",
"voucher_no",
"reposting_status_section",
"status",
"traceback"
],
"fields": [
{
"columns": 5,
"fieldname": "voucher_type",
"fieldtype": "Link",
"in_list_view": 1,
"label": "Voucher Type",
"options": "DocType"
"options": "DocType",
"reqd": 1
},
{
"fieldname": "column_break_ndex",
"fieldtype": "Column Break"
},
{
"columns": 5,
"fieldname": "voucher_no",
"fieldtype": "Dynamic Link",
"in_list_view": 1,
"label": "Voucher No",
"options": "voucher_type"
"options": "voucher_type",
"reqd": 1
},
{
"fieldname": "reposting_status_section",
"fieldtype": "Section Break",
"label": "Reposting Status"
},
{
"columns": 2,
"default": "Pending",
"fieldname": "status",
"fieldtype": "Select",
"in_list_view": 1,
"label": "Status",
"no_copy": 1,
"options": "Pending\nReposted\nSkipped\nFailed",
"read_only": 1
},
{
"fieldname": "traceback",
"fieldtype": "Code",
"label": "Traceback",
"no_copy": 1,
"read_only": 1
}
],
"index_web_pages_for_search": 1,
"istable": 1,
"links": [],
"modified": "2023-07-04 14:15:51.165584",
"modified": "2026-07-29 02:41:00.000000",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Repost Accounting Ledger Items",
@@ -37,4 +73,4 @@
"sort_field": "modified",
"sort_order": "DESC",
"states": []
}
}

View File

@@ -17,8 +17,10 @@ class RepostAccountingLedgerItems(Document):
parent: DF.Data
parentfield: DF.Data
parenttype: DF.Data
voucher_no: DF.DynamicLink | None
voucher_type: DF.Link | None
status: DF.Literal["Pending", "Reposted", "Skipped", "Failed"]
traceback: DF.Code | None
voucher_no: DF.DynamicLink
voucher_type: DF.Link
# end: auto-generated types
pass

View File

@@ -27,6 +27,7 @@ def start_payment_ledger_repost(docname=None):
"""
if docname:
repost_doc = frappe.get_doc("Repost Payment Ledger", docname)
repost_doc.check_permission("submit")
if repost_doc.docstatus.is_submitted() and repost_doc.repost_status in ["Queued", "Failed"]:
try:
for entry in repost_doc.repost_vouchers:
@@ -122,6 +123,8 @@ class RepostPaymentLedger(Document):
def execute_repost_payment_ledger(docname):
"""Repost Payment Ledger Entries by background job."""
frappe.has_permission("Repost Payment Ledger", ptype="submit", doc=docname, throw=True)
job_name = "payment_ledger_repost_" + docname
frappe.enqueue(

View File

@@ -375,9 +375,10 @@ erpnext.accounts.SalesInvoiceController = class SalesInvoiceController extends (
get_query_filters: {
docstatus: 1,
status: ["not in", ["Closed", "On Hold"]],
per_billed: ["<", 99.99],
company: me.frm.doc.company,
},
get_query_method:
"erpnext.selling.doctype.sales_order.sales_order.get_potentially_billable_sales_orders",
allow_child_item_selection: true,
child_fieldname: "items",
child_columns: ["item_code", "item_name", "qty", "amount", "billed_amt"],

View File

@@ -597,6 +597,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",
@@ -2198,7 +2199,7 @@
"link_fieldname": "consolidated_invoice"
}
],
"modified": "2026-04-06 22:30:28.513139",
"modified": "2026-08-12 12:00:00.000000",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Sales Invoice",

View File

@@ -25,9 +25,9 @@ from erpnext.accounts.doctype.tax_withholding_category.tax_withholding_category
from erpnext.accounts.general_ledger import get_round_off_account_and_cost_center
from erpnext.accounts.party import (
CROSS_PARTY_FIELD_NO_MAP,
_get_party_details,
get_due_date,
get_party_account,
get_party_details,
)
from erpnext.accounts.utils import (
cancel_exchange_gain_loss_journal,
@@ -1637,7 +1637,7 @@ class SalesInvoice(SellingController):
for payment_mode in self.payments:
if skip_change_gl_entries and payment_mode.account == self.account_for_change_amount:
payment_mode.base_amount -= flt(self.change_amount)
payment_mode.base_amount -= flt(self.base_change_amount)
against_voucher = self.name
if self.is_return and self.return_against and not self.update_outstanding_for_self:
@@ -2266,9 +2266,9 @@ def make_delivery_note(source_name, target_doc=None):
"cost_center": "cost_center",
},
"postprocess": update_item,
"condition": lambda doc: doc.delivered_by_supplier != 1
and not doc.dn_detail
and doc.qty - doc.delivered_qty > 0,
"condition": lambda doc: (
doc.delivered_by_supplier != 1 and not doc.dn_detail and doc.qty - doc.delivered_qty > 0
),
},
"Sales Taxes and Charges": {"doctype": "Sales Taxes and Charges", "reset_value": True},
"Sales Team": {
@@ -2737,7 +2737,7 @@ def update_taxes(
master_doctype=None,
):
# Update Party Details
party_details = get_party_details(
party_details = _get_party_details(
party=party,
party_type=party_type,
company=company,

View File

@@ -1235,6 +1235,33 @@ class TestSalesInvoice(FrappeTestCase):
frappe.db.set_single_value("Accounts Settings", "post_change_gl_entries", 1)
def test_pos_change_amount_multi_currency_gl_entry(self):
frappe.db.set_single_value("Accounts Settings", "post_change_gl_entries", 0)
si = create_sales_invoice(do_not_save=True)
si.is_pos = 1
si.currency = "USD"
si.conversion_rate = 50
si.party_account_currency = "USD"
si.account_for_change_amount = "Cash - _TC"
si.change_amount = 50
si.base_change_amount = 2500
si.append(
"payments",
{"mode_of_payment": "Cash", "account": "Cash - _TC", "amount": 150, "base_amount": 7500},
)
gl_entries = []
si.make_pos_gl_entries(gl_entries)
debtors_entry = next(entry for entry in gl_entries if entry["account"] == si.debit_to)
cash_entry = next(entry for entry in gl_entries if entry["account"] == "Cash - _TC")
self.assertEqual(flt(debtors_entry["credit"]), 5000.0)
self.assertEqual(flt(cash_entry["debit"]), 5000.0)
frappe.db.set_single_value("Accounts Settings", "post_change_gl_entries", 1)
def validate_pos_gl_entry(self, si, pos, cash_amount, validate_without_change_gle=False):
if validate_without_change_gle:
cash_amount -= pos.change_amount
@@ -2802,12 +2829,15 @@ class TestSalesInvoice(FrappeTestCase):
old_perpetual_inventory = erpnext.is_perpetual_inventory_enabled("_Test Company 1")
frappe.local.enable_perpetual_inventory["_Test Company 1"] = 1
old_inventory_account = frappe.db.get_value("Company", "_Test Company 1", "default_inventory_account")
frappe.db.set_value(
"Company",
"_Test Company 1",
"stock_received_but_not_billed",
"Stock Received But Not Billed - _TC1",
{
"stock_received_but_not_billed": "Stock Received But Not Billed - _TC1",
"default_inventory_account": "Stock In Hand - _TC1",
},
)
frappe.db.set_value(
"Company",
@@ -2852,6 +2882,7 @@ class TestSalesInvoice(FrappeTestCase):
# tear down
frappe.local.enable_perpetual_inventory["_Test Company 1"] = old_perpetual_inventory
frappe.db.set_value("Company", "_Test Company 1", "default_inventory_account", old_inventory_account)
frappe.db.set_single_value("Stock Settings", "allow_negative_stock", old_negative_stock)
def test_sle_for_target_warehouse(self):

View File

@@ -21,10 +21,12 @@
"rate",
"section_break_9",
"account_currency",
"net_amount",
"tax_amount",
"total",
"tax_amount_after_discount_amount",
"column_break_13",
"base_net_amount",
"base_tax_amount",
"base_total",
"base_tax_amount_after_discount_amount",
@@ -190,11 +192,11 @@
"fieldtype": "Column Break"
},
{
"allow_on_submit": 1,
"fieldname": "project",
"fieldtype": "Link",
"label": "Project",
"options": "Project"
"allow_on_submit": 1,
"fieldname": "project",
"fieldtype": "Link",
"label": "Project",
"options": "Project"
},
{
"default": "0",
@@ -220,19 +222,36 @@
"label": "Account Currency",
"options": "Currency",
"read_only": 1
},
{
"description": "Basis for tax calculation",
"fieldname": "net_amount",
"fieldtype": "Currency",
"label": "Net Amount",
"options": "currency",
"read_only": 1
},
{
"description": "Basis for tax calculation",
"fieldname": "base_net_amount",
"fieldtype": "Currency",
"label": "Net Amount (Company Currency)",
"options": "Company:company:default_currency",
"read_only": 1
}
],
"idx": 1,
"index_web_pages_for_search": 1,
"istable": 1,
"links": [],
"modified": "2024-01-14 10:08:17.776528",
"modified": "2026-05-01 00:37:57.880071",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Sales Taxes and Charges",
"owner": "Administrator",
"permissions": [],
"row_format": "Dynamic",
"sort_field": "modified",
"sort_order": "ASC",
"states": []
}
}

View File

@@ -16,6 +16,7 @@ class SalesTaxesandCharges(Document):
account_currency: DF.Link | None
account_head: DF.Link
base_net_amount: DF.Currency
base_tax_amount: DF.Currency
base_tax_amount_after_discount_amount: DF.Currency
base_total: DF.Currency
@@ -33,9 +34,11 @@ class SalesTaxesandCharges(Document):
included_in_paid_amount: DF.Check
included_in_print_rate: DF.Check
item_wise_tax_detail: DF.Code | None
net_amount: DF.Currency
parent: DF.Data
parentfield: DF.Data
parenttype: DF.Data
project: DF.Link | None
rate: DF.Float
row_id: DF.Data | None
tax_amount: DF.Currency

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

@@ -80,8 +80,7 @@
"fieldname": "cost_center",
"fieldtype": "Link",
"label": "Cost Center",
"options": "Cost Center",
"reqd": 1
"options": "Cost Center"
},
{
"fieldname": "shipping_amount_section",
@@ -139,18 +138,20 @@
"fieldtype": "Column Break"
},
{
"fieldname": "project",
"fieldtype": "Link",
"label": "Project",
"options": "Project"
"fieldname": "project",
"fieldtype": "Link",
"label": "Project",
"options": "Project"
}
],
"icon": "fa fa-truck",
"idx": 1,
"modified": "2019-05-25 23:12:26.156405",
"links": [],
"modified": "2026-07-22 14:53:27.315435",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Shipping Rule",
"naming_rule": "By fieldname",
"owner": "Administrator",
"permissions": [
{
@@ -196,5 +197,8 @@
"write": 1
}
],
"sort_order": "ASC"
}
"row_format": "Dynamic",
"sort_field": "creation",
"sort_order": "ASC",
"states": []
}

View File

@@ -36,18 +36,17 @@ class ShippingRule(Document):
from erpnext.accounts.doctype.shipping_rule_condition.shipping_rule_condition import (
ShippingRuleCondition,
)
from erpnext.accounts.doctype.shipping_rule_country.shipping_rule_country import (
ShippingRuleCountry,
)
from erpnext.accounts.doctype.shipping_rule_country.shipping_rule_country import ShippingRuleCountry
account: DF.Link
calculate_based_on: DF.Literal["Fixed", "Net Total", "Net Weight"]
company: DF.Link
conditions: DF.Table[ShippingRuleCondition]
cost_center: DF.Link
cost_center: DF.Link | None
countries: DF.Table[ShippingRuleCountry]
disabled: DF.Check
label: DF.Data
project: DF.Link | None
shipping_amount: DF.Currency
shipping_rule_type: DF.Literal["Selling", "Buying"]
# end: auto-generated types
@@ -162,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

@@ -96,3 +96,29 @@ frappe.ui.form.on("Subscription", {
});
},
});
frappe.ui.form.on("Subscription Plan Detail", {
plan: function (frm, cdt, cdn) {
const row = locals[cdt][cdn];
if (!row.plan) return;
const requested_plan = row.plan;
frappe.call({
method: "erpnext.accounts.doctype.subscription.subscription.get_plan_dimensions",
args: {
plan: requested_plan,
company: frm.doc.company,
party_type: frm.doc.party_type,
},
callback: function (r) {
if (!r.message || locals[cdt]?.[cdn]?.plan !== requested_plan) return;
// Only fill dimensions left empty, so a manual entry or an earlier plan is never overwritten.
for (const [dimension, value] of Object.entries(r.message)) {
if (frm.fields_dict[dimension] && !frm.doc[dimension]) {
frm.set_value(dimension, value);
}
}
},
});
},
});

View File

@@ -26,6 +26,7 @@ from erpnext.accounts.doctype.accounting_dimension.accounting_dimension import (
)
from erpnext.accounts.doctype.subscription_plan.subscription_plan import get_plan_rate
from erpnext.accounts.party import get_party_account_currency
from erpnext.stock.doctype.item.item import get_item_defaults
class InvoiceCancelled(frappe.ValidationError):
@@ -221,6 +222,9 @@ class Subscription(Document):
"""
Sets the status of the `Subscription`
"""
if self.status == "Cancelled":
return
if self.is_trialling():
self.status = "Trialling"
elif self.status == "Active" and self.end_date and getdate(posting_date) > getdate(self.end_date):
@@ -557,6 +561,11 @@ class Subscription(Document):
1. `process_for_active`
2. `process_for_past_due`
"""
# Snapshot before update_subscription_period() below can roll this forward,
# so the cancel_at_period_end check further down still targets the period
# that just ended, not the next one.
current_period_end = self.current_invoice_end
if not self.is_current_invoice_generated(
self.current_invoice_start, self.current_invoice_end
) and self.can_generate_new_invoice(posting_date):
@@ -566,8 +575,8 @@ class Subscription(Document):
self.update_subscription_period()
if self.cancel_at_period_end and (
getdate(posting_date) >= getdate(self.current_invoice_end)
or getdate(posting_date) >= getdate(self.end_date)
getdate(posting_date) >= getdate(current_period_end)
or (self.end_date and getdate(posting_date) >= getdate(self.end_date))
):
self.cancel_subscription()
@@ -747,6 +756,39 @@ def get_prorata_factor(
return diff / plan_days
@frappe.whitelist()
def get_plan_dimensions(
plan: str, company: str | None = None, party_type: str | None = None
) -> dict[str, str]:
"""Resolve a plan's accounting dimensions, falling back to the plan item's company defaults."""
plan_doc = frappe.get_cached_doc("Subscription Plan", plan)
dimensions = {}
for dimension in ["cost_center", *get_accounting_dimensions()]:
value = plan_doc.get(dimension) or get_item_dimension(plan_doc.item, dimension, company, party_type)
if value:
dimensions[dimension] = value
return dimensions
def get_item_dimension(
item_code: str, dimension: str, company: str | None, party_type: str | None
) -> str | None:
if not company:
return None
item_defaults = get_item_defaults(item_code, company)
if dimension != "cost_center":
return item_defaults.get(dimension)
selling = item_defaults.get("selling_cost_center")
buying = item_defaults.get("buying_cost_center")
if party_type == "Supplier":
return buying or selling
return selling or buying
def process_all(subscription: list, posting_date: DateTimeLikeObject | None = None) -> None:
"""
Task to updates the status of all `Subscription` apart from those that are cancelled

View File

@@ -17,7 +17,7 @@ from frappe.utils.data import (
nowdate,
)
from erpnext.accounts.doctype.subscription.subscription import get_prorata_factor
from erpnext.accounts.doctype.subscription.subscription import get_plan_dimensions, get_prorata_factor
test_dependencies = ("UOM", "Item Group", "Item")
@@ -280,6 +280,59 @@ class TestSubscription(FrappeTestCase):
settings.cancel_after_grace = default_grace_period_action
settings.save()
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="Beginning of the current subscription period"
)
subscription.process(posting_date=nowdate()) # generate first invoice
invoice = subscription.get_current_invoice()
self.assertIsNotNone(invoice)
invoice.db_set("outstanding_amount", 0)
invoice.db_set("status", "Paid")
subscription.cancel_subscription()
self.assertEqual(subscription.status, "Cancelled")
cancelation_date = getdate(subscription.cancelation_date)
subscription.set_subscription_status()
self.assertEqual(subscription.status, "Cancelled")
self.assertEqual(getdate(subscription.cancelation_date), cancelation_date)
subscription.cancel_at_period_end = 1
subscription.end_date = None
invoice_count = len(subscription.invoices)
subscription.process()
self.assertEqual(subscription.status, "Cancelled")
self.assertEqual(len(subscription.invoices), invoice_count)
def test_subscription_cancels_at_period_end_without_end_date(self):
# https://github.com/frappe/erpnext/issues/57761 -- generate_invoice() rolls
# current_invoice_end forward to the next period before this check runs, so
# with no end_date to fall back on, cancel_at_period_end must compare
# against the period that just ended, not the (already advanced) next one.
create_plan(
plan_name="_Test plan name 11",
cost=80,
currency="INR",
billing_interval="Day",
billing_interval_count=3,
)
subscription = create_subscription(
start_date=nowdate(),
generate_invoice_at="End of the current subscription period",
plans=[{"plan": "_Test plan name 11", "qty": 1}],
)
subscription.cancel_at_period_end = 1
self.assertEqual(len(subscription.invoices), 0)
period_end = subscription.current_invoice_end
subscription.process(posting_date=period_end)
self.assertEqual(subscription.status, "Cancelled")
self.assertEqual(len(subscription.invoices), 1)
def test_subscription_restart_and_process(self):
settings = frappe.get_single("Subscription Settings")
default_grace_period_action = settings.cancel_after_grace
@@ -583,6 +636,48 @@ class TestSubscription(FrappeTestCase):
subscription.process(nowdate())
self.assertEqual(len(subscription.invoices), 1)
def test_plan_dimensions_resolve_from_plan_then_item(self):
from erpnext.stock.doctype.item.test_item import make_item
# Plan-level cost center takes precedence.
create_plan(plan_name="_Test Sub Plan CC", cost=100, currency="INR")
frappe.db.set_value(
"Subscription Plan", "_Test Sub Plan CC", "cost_center", "_Test Cost Center - _TC"
)
self.assertEqual(
get_plan_dimensions("_Test Sub Plan CC", "_Test Company", "Customer").get("cost_center"),
"_Test Cost Center - _TC",
)
# No plan cost center: fall back to the item's company default (selling vs buying by party type).
item = make_item(
"_Test Sub Dimension Item",
{
"is_stock_item": 0,
"item_defaults": [
{
"company": "_Test Company",
"default_warehouse": "_Test Warehouse - _TC",
"selling_cost_center": "_Test Cost Center - _TC",
"buying_cost_center": "_Test Cost Center 2 - _TC",
}
],
},
)
create_plan(plan_name="_Test Sub Plan No CC", cost=100, currency="INR", item=item.name)
self.assertEqual(
get_plan_dimensions("_Test Sub Plan No CC", "_Test Company", "Customer").get("cost_center"),
"_Test Cost Center - _TC",
)
self.assertEqual(
get_plan_dimensions("_Test Sub Plan No CC", "_Test Company", "Supplier").get("cost_center"),
"_Test Cost Center 2 - _TC",
)
# Without a company the item fallback is skipped.
self.assertNotIn("cost_center", get_plan_dimensions("_Test Sub Plan No CC"))
def make_plans():
create_plan(plan_name="_Test Plan Name", cost=900, currency="INR")

View File

@@ -83,7 +83,6 @@ def get_party_details(
price_list=None,
currency=None,
doctype=None,
ignore_permissions=False,
fetch_payment_terms_template=True,
party_address=None,
company_address=None,
@@ -93,8 +92,6 @@ def get_party_details(
):
if not party:
return frappe._dict()
if not frappe.db.exists(party_type, party):
frappe.throw(_("{0}: {1} does not exists").format(party_type, party))
return _get_party_details(
party,
account,
@@ -105,7 +102,7 @@ def get_party_details(
price_list,
currency,
doctype,
ignore_permissions,
False,
fetch_payment_terms_template,
party_address,
company_address,
@@ -849,9 +846,11 @@ def validate_account_party_type(self):
def get_dashboard_info(party_type, party, loyalty_program=None):
current_fiscal_year = get_fiscal_year(nowdate(), as_dict=True)
doctype = "Sales Invoice" if party_type == "Customer" else "Purchase Invoice"
if not frappe.has_permission(doctype, "read"):
return None
current_fiscal_year = get_fiscal_year(nowdate(), as_dict=True)
companies = frappe.get_list(
doctype, filters={"docstatus": 1, party_type.lower(): party}, distinct=1, fields=["company"]

View File

@@ -94,10 +94,15 @@ frappe.query_reports["Accounts Payable"] = {
options: get_party_type_options(),
on_change: function () {
frappe.query_report.set_filter_value("party", "");
frappe.query_report.toggle_filter_display(
"supplier_group",
frappe.query_report.get_filter_value("party_type") !== "Supplier"
);
let is_supplier = frappe.query_report.get_filter_value("party_type") === "Supplier";
let supplier_group_filter = frappe.query_report.get_filter("supplier_group");
if (supplier_group_filter) {
supplier_group_filter.df.hidden = !is_supplier;
}
frappe.query_report.toggle_filter_display("supplier_group", !is_supplier);
if (!is_supplier) {
frappe.query_report.set_filter_value("supplier_group", []);
}
},
},
{
@@ -117,8 +122,11 @@ frappe.query_reports["Accounts Payable"] = {
{
fieldname: "supplier_group",
label: __("Supplier Group"),
fieldtype: "Link",
fieldtype: "MultiSelectList",
options: "Supplier Group",
get_data: function (txt) {
return frappe.db.get_link_options("Supplier Group", txt);
},
hidden: 1,
},
{

View File

@@ -121,6 +121,36 @@ class TestAccountsPayable(AccountsTestMixin, FrappeTestCase):
self.assertEqual(len(report[1]), 2)
self.assertEqual([pi.name, payment_term1.payment_term_name], [row.voucher_no, row.payment_term])
def test_supplier_group_filter(self):
pi = self.create_purchase_invoice()
supplier_group = frappe.db.get_value("Supplier", self.supplier, "supplier_group")
other_group = frappe.get_doc(
doctype="Supplier Group",
supplier_group_name="_Test Supplier Group AP",
parent_supplier_group="All Supplier Groups",
).insert()
filters = {
"company": self.company,
"party_type": "Supplier",
"report_date": today(),
"range": "30, 60, 90, 120",
"supplier_group": supplier_group,
}
self.assertIn(pi.name, [row.voucher_no for row in execute(filters)[1]])
filters.update({"supplier_group": [other_group.name]})
self.assertEqual(len(execute(filters)[1]), 0)
filters.update({"supplier_group": [supplier_group, other_group.name]})
self.assertIn(pi.name, [row.voucher_no for row in execute(filters)[1]])
filters.update({"supplier_group": ["All Supplier Groups"]})
self.assertIn(pi.name, [row.voucher_no for row in execute(filters)[1]])
filters.update({"supplier_group": ["_Test Supplier Group Mars"]})
self.assertRaises(frappe.ValidationError, execute, filters)
def test_project_filter(self):
project = frappe.get_doc(
{"doctype": "Project", "project_name": "_Test AP Project", "company": self.company}

View File

@@ -100,8 +100,11 @@ frappe.query_reports["Accounts Payable Summary"] = {
{
fieldname: "supplier_group",
label: __("Supplier Group"),
fieldtype: "Link",
fieldtype: "MultiSelectList",
options: "Supplier Group",
get_data: function (txt) {
return frappe.db.get_link_options("Supplier Group", txt);
},
},
{
fieldname: "based_on_payment_terms",

View File

@@ -140,8 +140,11 @@ frappe.query_reports["Accounts Receivable"] = {
{
fieldname: "territory",
label: __("Territory"),
fieldtype: "Link",
fieldtype: "MultiSelectList",
options: "Territory",
get_data: function (txt) {
return frappe.db.get_link_options("Territory", txt);
},
},
{
fieldname: "group_by_party",

View File

@@ -106,6 +106,7 @@ class ReceivablePayableReport:
def get_data(self):
self.get_sales_invoices_or_customers_based_on_sales_person()
self.get_invoices_based_on_sales_partner()
# Get invoice details like bill_no, due_date etc for all invoices
self.get_invoice_details()
@@ -166,6 +167,7 @@ class ReceivablePayableReport:
party_account=ple.account,
posting_date=ple.posting_date,
account_currency=ple.account_currency,
cost_center=ple.cost_center,
remarks=ple.remarks,
invoiced=0.0,
paid=0.0,
@@ -241,6 +243,12 @@ class ReceivablePayableReport:
):
return
if self.filters.get("sales_partner"):
# a return is folded onto the invoice it settles, so match that invoice's
# partner (like the sales_person filter above), not the return's own
if ple.against_voucher_no not in self.sales_partner_invoices:
return
if self.filters.get("ignore_accounts"):
key = (ple.against_voucher_type, ple.against_voucher_no, ple.party)
else:
@@ -469,7 +477,7 @@ class ReceivablePayableReport:
"company": self.filters.company,
"docstatus": 1,
},
fields=["name", "due_date", "po_no"],
fields=["name", "due_date", "po_no", "sales_partner"],
)
for d in si_list:
self.invoice_details.setdefault(d.name, d)
@@ -903,6 +911,22 @@ class ReceivablePayableReport:
for d in records:
self.sales_person_records.setdefault(d.parenttype, set()).add(d.parent)
def get_invoices_based_on_sales_partner(self):
if not self.filters.get("sales_partner"):
return
self.sales_partner_invoices = set(
frappe.get_all(
"Sales Invoice",
filters={
"sales_partner": self.filters.get("sales_partner"),
"docstatus": 1,
"company": self.filters.company,
},
pluck="name",
)
)
def prepare_conditions(self):
self.qb_selection_filter = []
self.or_filters = []
@@ -990,7 +1014,13 @@ class ReceivablePayableReport:
self.qb_selection_filter.append(self.ple.party.isin(customers))
if self.filters.get("territory"):
self.get_hierarchical_filters("Territory", "territory")
territories = get_nested_set_children("Territory", self.filters.territory)
customers = (
qb.from_(self.customer)
.select(self.customer.name)
.where(self.customer["territory"].isin(territories))
)
self.qb_selection_filter.append(self.ple.party.isin(customers))
if self.filters.get("payment_terms_template"):
customer_ptt = self.ple.party.isin(
@@ -1005,26 +1035,16 @@ class ReceivablePayableReport:
self.qb_selection_filter.append(Criterion.any([customer_ptt, sales_ptt]))
if self.filters.get("sales_partner"):
self.qb_selection_filter.append(
self.ple.party.isin(
qb.from_(self.customer)
.select(self.customer.name)
.where(self.customer.default_sales_partner == self.filters.get("sales_partner"))
)
)
def exclude_employee_transaction(self):
self.qb_selection_filter.append(self.ple.party_type != "Employee")
def add_supplier_filters(self):
supplier = qb.DocType("Supplier")
if self.filters.get("supplier_group"):
groups = get_party_group_with_children("Supplier", self.filters.supplier_group)
self.qb_selection_filter.append(
self.ple.party.isin(
qb.from_(supplier)
.select(supplier.name)
.where(supplier.supplier_group == self.filters.get("supplier_group"))
qb.from_(supplier).select(supplier.name).where(supplier.supplier_group.isin(groups))
)
)
@@ -1076,16 +1096,6 @@ class ReceivablePayableReport:
return ptt
def get_hierarchical_filters(self, doctype, key):
lft, rgt = frappe.db.get_value(doctype, self.filters.get(key), ["lft", "rgt"])
doc = qb.DocType(doctype)
ple = self.ple
customer = self.customer
groups = qb.from_(doc).select(doc.name).where((doc.lft >= lft) & (doc.rgt <= rgt))
customers = qb.from_(customer).select(customer.name).where(customer[key].isin(groups))
self.qb_selection_filter.append(ple.party.isin(customers))
def add_accounting_dimensions_filters(self):
accounting_dimensions = get_accounting_dimensions(as_list=False)
@@ -1113,9 +1123,6 @@ class ReceivablePayableReport:
if self.account_type == "Receivable":
fields = ["customer_name", "territory", "customer_group", "customer_primary_contact"]
if self.filters.get("sales_partner"):
fields.append("default_sales_partner")
self.party_details[party] = frappe.db.get_value(
"Customer",
party,
@@ -1242,7 +1249,7 @@ class ReceivablePayableReport:
self.add_column(label=_("Sales Person"), fieldname="sales_person", fieldtype="Data")
if self.filters.sales_partner:
self.add_column(label=_("Sales Partner"), fieldname="default_sales_partner", fieldtype="Data")
self.add_column(label=_("Sales Partner"), fieldname="sales_partner", fieldtype="Data")
if self.filters.account_type == "Payable":
self.add_column(
@@ -1318,19 +1325,23 @@ def get_party_group_with_children(party, party_groups):
if party not in ("Customer", "Supplier"):
return []
group_dtype = f"{party} Group"
if not isinstance(party_groups, list):
party_groups = [d.strip() for d in party_groups.strip().split(",") if d]
return get_nested_set_children(f"{party} Group", party_groups)
all_party_groups = []
for d in party_groups:
if frappe.db.exists(group_dtype, d):
lft, rgt = frappe.db.get_value(group_dtype, d, ["lft", "rgt"])
children = frappe.get_all(
group_dtype, filters={"lft": [">=", lft], "rgt": ["<=", rgt]}, pluck="name"
)
all_party_groups += children
def get_nested_set_children(doctype, values):
if not isinstance(values, list):
values = [d.strip() for d in values.split(",") if d.strip()]
if not values:
frappe.throw(_("Please select a valid {0}").format(_(doctype)))
all_values = []
for d in values:
if frappe.db.exists(doctype, d):
lft, rgt = frappe.db.get_value(doctype, d, ["lft", "rgt"])
children = frappe.get_all(doctype, filters={"lft": [">=", lft], "rgt": ["<=", rgt]}, pluck="name")
all_values += children
else:
frappe.throw(_("{0}: {1} does not exist").format(group_dtype, d))
frappe.throw(_("{0}: {1} does not exist").format(doctype, d))
return list(set(all_party_groups))
return list(set(all_values))

View File

@@ -7,6 +7,7 @@ from erpnext.accounts.doctype.payment_entry.payment_entry import get_payment_ent
from erpnext.accounts.doctype.sales_invoice.test_sales_invoice import create_sales_invoice
from erpnext.accounts.report.accounts_receivable.accounts_receivable import execute
from erpnext.accounts.test.accounts_mixin import AccountsTestMixin
from erpnext.controllers.sales_and_purchase_return import make_return_doc
from erpnext.selling.doctype.sales_order.test_sales_order import make_sales_order
@@ -770,6 +771,38 @@ class TestAccountsReceivable(AccountsTestMixin, FrappeTestCase):
# Assert that the customer group of each row is in the list of customer groups
self.assertIn(row.customer_group, cus_groups_list)
def test_territory_filter(self):
self.create_sales_invoice()
territory = frappe.db.get_value("Customer", self.customer, "territory")
filters = {
"company": self.company,
"report_date": today(),
"range": "30, 60, 90, 120",
"territory": territory,
}
report = execute(filters)[1]
self.assertEqual(len(report), 1)
self.assertEqual(
[100.0, 100.0, territory], [report[0].invoiced, report[0].outstanding, report[0].territory]
)
filters.update({"territory": ["_Test Territory United States"]})
self.assertEqual(len(execute(filters)[1]), 0)
filters.update({"territory": [territory, "_Test Territory United States"]})
self.assertEqual(len(execute(filters)[1]), 1)
frappe.db.set_value("Customer", self.customer, "territory", "_Test Territory Maharashtra")
filters.update({"territory": ["_Test Territory India"]})
self.assertEqual(len(execute(filters)[1]), 1)
filters.update({"territory": ["_Test Territory Mars"]})
self.assertRaises(frappe.ValidationError, execute, filters)
filters.update({"territory": " "})
self.assertRaises(frappe.ValidationError, execute, filters)
def test_party_account_filter(self):
si1 = self.create_sales_invoice()
self.customer2 = (
@@ -1142,6 +1175,28 @@ class TestAccountsReceivable(AccountsTestMixin, FrappeTestCase):
row = report[1][0]
self.assertEqual(expected_data_after_payment, [row.voucher_no, row.cost_center, row.outstanding])
def test_cost_center_on_payment_before_invoice(self):
filters = {
"company": self.company,
"party_type": "Customer",
"party": [self.customer],
"report_date": today(),
"range": "30, 60, 90, 120",
}
si = self.create_sales_invoice(no_payment_schedule=True, do_not_submit=True)
si.posting_date = add_days(today(), 1)
si.due_date = si.posting_date
si.payment_schedule[0].due_date = si.posting_date
si.save().submit()
pe = self.create_payment_entry(si.name, do_not_submit=True)
pe.cost_center = self.cost_center
pe.save().submit()
row = next(row for row in execute(filters)[1] if row.voucher_no == pe.name)
self.assertEqual(row.cost_center, pe.cost_center)
def test_payment_terms_template_filters(self):
from erpnext.controllers.accounts_controller import get_payment_terms
@@ -1303,3 +1358,61 @@ class TestAccountsReceivable(AccountsTestMixin, FrappeTestCase):
self.assertIn(original_customer, parties)
self.assertNotIn(second_customer, parties)
self.assertEqual(allowed_invoice.customer, original_customer)
def test_receivable_filtered_by_sales_partner(self):
frappe.set_user("Administrator")
partner_a, partner_b = "_Test AR Sales Partner A", "_Test AR Sales Partner B"
for partner in (partner_a, partner_b):
if not frappe.db.exists("Sales Partner", partner):
frappe.get_doc(
{
"doctype": "Sales Partner",
"partner_name": partner,
"commission_rate": 0,
"territory": "All Territories",
}
).insert()
def _si(sales_partner):
si = self.create_sales_invoice(no_payment_schedule=True, do_not_submit=True, qty=2)
si.sales_partner = sales_partner
return si.save().submit()
partner_a_si = _si(partner_a)
partner_b_si = _si(partner_b)
no_partner_si = _si(None)
# a return is folded onto the invoice it settles, so it nets against that
# invoice's partner even when the return's own partner is cleared
no_partner_return = make_return_doc("Sales Invoice", partner_a_si.name)
no_partner_return.sales_partner = None
no_partner_return.items[0].qty = -1
no_partner_return.update_outstanding_for_self = 0
no_partner_return.save().submit()
filters = {
"company": self.company,
"party_type": "Customer",
"report_date": today(),
"range": "30, 60, 90, 120",
}
def rows_for(partner):
return {
r.voucher_no: r
for r in execute({**filters, "sales_partner": partner})[1]
if r.get("voucher_no")
}
rows_a = rows_for(partner_a)
self.assertIn(partner_a_si.name, rows_a)
self.assertEqual(rows_a[partner_a_si.name].sales_partner, partner_a)
self.assertNotIn(partner_b_si.name, rows_a)
self.assertNotIn(no_partner_si.name, rows_a)
self.assertNotIn(no_partner_return.name, rows_a)
self.assertEqual(rows_a[partner_a_si.name].credit_note, 100)
self.assertEqual(rows_a[partner_a_si.name].outstanding, 100)
rows_b = rows_for(partner_b)
self.assertIn(partner_b_si.name, rows_b)
self.assertNotIn(partner_a_si.name, rows_b)

View File

@@ -106,8 +106,11 @@ frappe.query_reports["Accounts Receivable Summary"] = {
{
fieldname: "territory",
label: __("Territory"),
fieldtype: "Link",
fieldtype: "MultiSelectList",
options: "Territory",
get_data: function (txt) {
return frappe.db.get_link_options("Territory", txt);
},
},
{
fieldname: "sales_partner",

View File

@@ -132,8 +132,8 @@ class AccountsReceivableSummary(ReceivablePayableReport):
if row.sales_person:
self.party_total[row.party].sales_person.append(row.get("sales_person", ""))
if self.filters.sales_partner:
self.party_total[row.party]["default_sales_partner"] = row.get("default_sales_partner", "")
if self.filters.sales_partner and row.get("sales_partner"):
self.party_total[row.party]["sales_partner"] = row.get("sales_partner")
def get_columns(self):
self.columns = []
@@ -191,7 +191,7 @@ class AccountsReceivableSummary(ReceivablePayableReport):
self.add_column(label=_("Sales Person"), fieldname="sales_person", fieldtype="Data")
if self.filters.sales_partner:
self.add_column(label=_("Sales Partner"), fieldname="default_sales_partner", fieldtype="Data")
self.add_column(label=_("Sales Partner"), fieldname="sales_partner", fieldtype="Data")
else:
self.add_column(

View File

@@ -193,3 +193,42 @@ class TestAccountsReceivable(AccountsTestMixin, FrappeTestCase):
report = execute(filters)
rpt_output = report[1]
self.assertEqual(len(rpt_output), 0)
def test_03_summary_sales_partner_column(self):
partner = "_Test AR Summary Sales Partner"
if not frappe.db.exists("Sales Partner", partner):
frappe.get_doc(
{
"doctype": "Sales Partner",
"partner_name": partner,
"commission_rate": 0,
"territory": "All Territories",
}
).insert()
si = create_sales_invoice(
item=self.item,
company=self.company,
customer=self.customer,
debit_to=self.debit_to,
posting_date=today(),
parent_cost_center=self.cost_center,
cost_center=self.cost_center,
rate=200,
price_list_rate=200,
do_not_submit=True,
)
si.sales_partner = partner
si.save().submit()
filters = {
"company": self.company,
"customer": self.customer,
"posting_date": today(),
"range": "30, 60, 90, 120",
"sales_partner": partner,
}
rpt_output = execute(filters)[1]
self.assertEqual(len(rpt_output), 1)
self.assertEqual(rpt_output[0].get("sales_partner"), partner)

View File

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

View File

@@ -93,5 +93,27 @@ frappe.query_reports["Customer Ledger Summary"] = {
fieldtype: "Data",
hidden: 1,
},
{
fieldname: "cost_center",
label: __("Cost Center"),
fieldtype: "MultiSelectList",
options: "Cost Center",
get_data: function (txt) {
return frappe.db.get_link_options("Cost Center", txt, {
company: frappe.query_report.get_filter_value("company"),
});
},
},
{
fieldname: "project",
label: __("Project"),
fieldtype: "MultiSelectList",
options: "Project",
get_data: function (txt) {
return frappe.db.get_link_options("Project", txt, {
company: frappe.query_report.get_filter_value("company"),
});
},
},
],
};

View File

@@ -174,7 +174,7 @@ frappe.query_reports["General Ledger"] = {
fieldname: "include_dimensions",
label: __("Consider Accounting Dimensions"),
fieldtype: "Check",
default: 1,
default: frappe.boot.sysdefaults.disable_include_dimensions ? 0 : 1,
},
{
fieldname: "disable_opening_balance_calculation",

View File

@@ -180,13 +180,15 @@ def get_data_when_grouped_by_invoice(columns, gross_profit_data, filters, group_
columns[0]["fieldname"] = "sales_invoice"
columns[0]["options"] = "Item"
columns[0]["width"] = 300
# removing Item Code and Item Name columns
# removing the duplicate Item Code column and moving Item Name before Customer
supplier_master_name = frappe.db.get_single_value("Buying Settings", "supp_master_name")
customer_master_name = frappe.db.get_single_value("Selling Settings", "cust_master_name")
if supplier_master_name == "Supplier Name" and customer_master_name == "Customer Name":
del columns[4:6]
del columns[4]
columns.insert(1, columns.pop(4))
else:
del columns[5:7]
del columns[5]
columns.insert(1, columns.pop(5))
total_base_amount = 0
total_buying_amount = 0
@@ -510,6 +512,7 @@ class GrossProfitGenerator:
self.average_buying_rate = {}
self.filters = frappe._dict(filters)
self.load_invoice_items()
self.load_drop_ship_buying_rates()
self.get_delivery_notes()
self.load_product_bundle()
@@ -518,6 +521,7 @@ class GrossProfitGenerator:
self.load_non_stock_items()
self.get_returned_invoice_items()
self.allocate_legacy_return_items()
self.process()
def process(self):
@@ -534,6 +538,8 @@ class GrossProfitGenerator:
base_amount = 0
for row in reversed(self.si_list):
sales_invoice_item = row.item_row
if self.filters.get("group_by") == "Monthly":
row.monthly = formatdate(row.posting_date, "MMM YYYY")
@@ -585,14 +591,18 @@ class GrossProfitGenerator:
# get buying rate
if flt(row.qty):
row.buying_rate = flt(row.buying_amount / flt(row.qty), self.float_precision)
row.buying_rate = (
flt(row.buying_amount / flt(row.qty), self.float_precision)
if not row.delivered_by_supplier
else None
)
row.base_rate = flt(row.base_amount / flt(row.qty), self.float_precision)
else:
if self.is_not_invoice_row(row):
row.buying_rate, row.base_rate = 0.0, 0.0
if self.is_not_invoice_row(row):
self.update_return_invoices(row)
self.update_return_invoices(row, sales_invoice_item)
if grouped_by_invoice and row.indent == 1.0:
buying_amount += row.buying_amount
@@ -619,24 +629,31 @@ class GrossProfitGenerator:
if self.grouped:
self.get_average_rate_based_on_group_by()
def update_return_invoices(self, row):
if row.parent in self.returned_invoices and row.item_code in self.returned_invoices[row.parent]:
returned_item_rows = self.returned_invoices[row.parent][row.item_code]
for returned_item_row in returned_item_rows:
# returned_items 'qty' should be stateful
if returned_item_row.qty != 0:
if row.qty >= abs(returned_item_row.qty):
row.qty += returned_item_row.qty
row.base_amount += flt(returned_item_row.base_amount, self.currency_precision)
returned_item_row.qty = 0
returned_item_row.base_amount = 0
def update_return_invoices(self, row, sales_invoice_item):
returned_item_rows = self.returned_invoices.get(row.parent, {}).get(sales_invoice_item)
if not returned_item_rows:
return
else:
row.qty = 0
row.base_amount = 0
returned_item_row.qty += row.qty
returned_item_row.base_amount += row.base_amount
for returned_item_row in returned_item_rows:
# returned_items 'qty' should be stateful
if returned_item_row.qty != 0:
if row.qty >= abs(returned_item_row.qty):
row.qty += returned_item_row.qty
row.base_amount += flt(returned_item_row.base_amount, self.currency_precision)
returned_item_row.qty = 0
returned_item_row.base_amount = 0
else:
returned_item_row.qty += row.qty
returned_item_row.base_amount += row.base_amount
row.qty = 0
row.base_amount = 0
if row.delivered_by_supplier:
buying_amount = self.get_drop_ship_buying_amount(row)
if buying_amount is not None:
row.buying_amount = flt(buying_amount, self.currency_precision)
else:
row.buying_amount = flt(flt(row.qty) * flt(row.buying_rate), self.currency_precision)
def get_average_rate_based_on_group_by(self):
@@ -718,7 +735,8 @@ class GrossProfitGenerator:
returned_invoices = frappe.db.sql(
"""
select
si.name, si_item.item_code, si_item.stock_qty as qty, si_item.base_net_amount as base_amount, si.return_against
si.name, si_item.item_code, si_item.sales_invoice_item,
si_item.stock_qty as qty, si_item.base_net_amount as base_amount, si.return_against
from
`tabSales Invoice` si, `tabSales Invoice Item` si_item
where
@@ -732,17 +750,73 @@ class GrossProfitGenerator:
)
self.returned_invoices = frappe._dict()
self.legacy_returned_invoices = frappe._dict()
for inv in returned_invoices:
self.returned_invoices.setdefault(inv.return_against, frappe._dict()).setdefault(
inv.item_code, []
invoice_returns = (
self.returned_invoices if inv.sales_invoice_item else self.legacy_returned_invoices
)
invoice_returns.setdefault(inv.return_against, frappe._dict()).setdefault(
inv.sales_invoice_item or inv.item_code, []
).append(inv)
def skip_row(self, row):
if self.filters.get("group_by") != "Invoice":
if not row.get(scrub(self.filters.get("group_by", ""))):
return True
def allocate_legacy_return_items(self):
source_invoice_items = {}
for row in reversed(self.si_list):
if row.is_return or not row.parent or self.skip_row(row):
continue
return False
source_invoice_items.setdefault((row.parent, row.item_code), {}).setdefault(row.item_row, row.qty)
for invoice, legacy_invoice_items in self.legacy_returned_invoices.items():
returned_invoice_items = self.returned_invoices.setdefault(invoice, frappe._dict())
for item_code, legacy_item_rows in legacy_invoice_items.items():
targets = self.get_legacy_return_targets(
source_invoice_items.get((invoice, item_code), {}), returned_invoice_items
)
for legacy_item_row in legacy_item_rows:
self.allocate_legacy_return_item(legacy_item_row, targets, returned_invoice_items)
def get_legacy_return_targets(self, source_invoice_items, returned_invoice_items):
targets = []
for item_row, qty in source_invoice_items.items():
linked_return_qty = sum(
flt(returned_item.qty) for returned_item in returned_invoice_items.get(item_row, [])
)
if available_qty := max(flt(qty) + linked_return_qty, 0):
targets.append(frappe._dict(item_row=item_row, available_qty=available_qty))
targets.sort(key=lambda target: bool(returned_invoice_items.get(target.item_row)))
return targets
def allocate_legacy_return_item(self, legacy_item_row, targets, returned_invoice_items):
remaining_qty = abs(flt(legacy_item_row.qty))
remaining_base_amount = flt(legacy_item_row.base_amount)
if not remaining_qty:
return
qty_sign = -1 if legacy_item_row.qty < 0 else 1
for target in targets:
if not target.available_qty:
continue
allocated_qty = min(target.available_qty, remaining_qty)
allocated_item_row = frappe._dict(legacy_item_row.copy())
allocated_item_row.qty = qty_sign * allocated_qty
allocated_item_row.base_amount = remaining_base_amount * allocated_qty / remaining_qty
returned_invoice_items.setdefault(target.item_row, []).append(allocated_item_row)
target.available_qty -= allocated_qty
remaining_qty -= allocated_qty
remaining_base_amount -= allocated_item_row.base_amount
if not remaining_qty:
break
def skip_row(self, row):
group_by = self.filters.get("group_by")
if group_by in {"Invoice", "Monthly"}:
return False
return not row.get(scrub(group_by))
def get_buying_amount_from_product_bundle(self, row, product_bundle):
buying_amount = 0.0
@@ -776,6 +850,11 @@ class GrossProfitGenerator:
# IMP NOTE
# stock_ledger_entries should already be filtered by item_code and warehouse and
# sorted by posting_date desc, posting_time desc
if row.delivered_by_supplier:
buying_amount = self.get_drop_ship_buying_amount(row)
if buying_amount is not None:
return buying_amount
if item_code in self.non_stock_items and (row.project or row.cost_center):
# Issue 6089-Get last purchasing rate for non-stock item
item_rate = self.get_last_purchase_rate(item_code, row)
@@ -807,6 +886,49 @@ class GrossProfitGenerator:
return flt(row.qty) * self.get_average_buying_rate(row, item_code)
def load_drop_ship_buying_rates(self):
self.drop_ship_buying_rates = {}
sales_order_items = {
row.so_detail for row in self.si_list if row.delivered_by_supplier and row.so_detail
}
if not sales_order_items:
return
from frappe.query_builder.functions import Sum
purchase_order_item = frappe.qb.DocType("Purchase Order Item")
purchase_invoice_item = frappe.qb.DocType("Purchase Invoice Item")
buying_amounts = (
frappe.qb.from_(purchase_order_item)
.left_join(purchase_invoice_item)
.on(
(purchase_invoice_item.po_detail == purchase_order_item.name)
& (purchase_invoice_item.docstatus == 1)
)
.select(
purchase_order_item.sales_order_item,
Sum(purchase_invoice_item.qty * purchase_invoice_item.base_net_rate).as_("buying_amount"),
Sum(purchase_invoice_item.stock_qty).as_("stock_qty"),
)
.where(
(purchase_order_item.sales_order_item.isin(sales_order_items))
& (purchase_order_item.docstatus == 1)
)
.groupby(purchase_order_item.sales_order_item)
.run(as_dict=True)
)
for row in buying_amounts:
self.drop_ship_buying_rates[row.sales_order_item] = (
flt(row.buying_amount) / flt(row.stock_qty) if flt(row.stock_qty) else 0
)
def get_drop_ship_buying_amount(self, row):
if row.so_detail not in self.drop_ship_buying_rates:
return
return flt(row.qty) * self.drop_ship_buying_rates[row.so_detail]
def get_buying_amount_from_so_dn(self, sales_order, so_detail, item_code):
from frappe.query_builder.functions import Avg
@@ -951,6 +1073,7 @@ class GrossProfitGenerator:
SalesInvoice.is_return,
SalesInvoiceItem.cost_center,
SalesInvoiceItem.serial_and_batch_bundle,
SalesInvoiceItem.delivered_by_supplier,
)
if self.filters.group_by == "Sales Person":

View File

@@ -1,16 +1,18 @@
import frappe
from frappe import qb
from frappe.tests.utils import FrappeTestCase
from frappe.tests.utils import FrappeTestCase, change_settings
from frappe.utils import add_days, flt, get_first_day, get_last_day, nowdate
from erpnext.accounts.doctype.sales_invoice.sales_invoice import make_delivery_note, make_sales_return
from erpnext.accounts.doctype.sales_invoice.test_sales_invoice import create_sales_invoice
from erpnext.accounts.report.gross_profit.gross_profit import execute
from erpnext.accounts.report.gross_profit.gross_profit import GrossProfitGenerator, execute
from erpnext.stock.doctype.delivery_note.delivery_note import make_sales_invoice
from erpnext.stock.doctype.delivery_note.test_delivery_note import create_delivery_note
from erpnext.stock.doctype.item.test_item import create_item
from erpnext.stock.doctype.stock_entry.stock_entry_utils import make_stock_entry
test_dependencies = ["Purchase Invoice", "Sales Invoice"]
class TestGrossProfit(FrappeTestCase):
def setUp(self):
@@ -881,6 +883,377 @@ class TestGrossProfit(FrappeTestCase):
self.assertEqual(gross_profit, 120.0) # 220 - 100
self.assertAlmostEqual(gp_percent, 54.545, places=2) # 120/220 * 100
def test_drop_ship(self):
from erpnext.selling.doctype.sales_order.sales_order import make_sales_invoice
so = self.create_drop_ship_order()
si = make_sales_invoice(so.name).submit()
filters = frappe._dict(
company=si.company, from_date=si.posting_date, to_date=si.posting_date, group_by="Invoice"
)
_, data = execute(filters=filters)
self.assertEqual(data[1].buying_amount, 800)
self.assertIsNone(data[1].buying_rate)
self.assertEqual(data[1]["gross_profit_%"], 20)
def test_drop_ship_partial_billing_and_return(self):
from erpnext.selling.doctype.sales_order.sales_order import make_sales_invoice
so = self.create_drop_ship_order()
first_invoice = make_sales_invoice(so.name)
first_invoice.items[0].qty = 4
first_invoice.submit()
second_invoice = make_sales_invoice(so.name).submit()
filters = frappe._dict(
company=first_invoice.company,
from_date=first_invoice.posting_date,
to_date=first_invoice.posting_date,
group_by="Invoice",
)
_, data = execute(filters=filters)
invoice_rows = {
row.parent_invoice: row
for row in data
if row.parent_invoice in {first_invoice.name, second_invoice.name} and row.indent == 1
}
self.assertEqual(invoice_rows[first_invoice.name].buying_amount, 320)
self.assertEqual(invoice_rows[second_invoice.name].buying_amount, 480)
sales_return = make_sales_return(first_invoice.name)
sales_return.items[0].qty = -2
sales_return.submit()
_, data = execute(filters=filters)
first_invoice_row = next(
row for row in data if row.parent_invoice == first_invoice.name and row.indent == 1
)
self.assertEqual(first_invoice_row.qty, 2)
self.assertEqual(first_invoice_row.buying_amount, 160)
self.assertEqual(first_invoice_row.gross_profit, 40)
def test_drop_ship_return_matches_sales_invoice_item(self):
from erpnext.buying.doctype.purchase_order.purchase_order import make_purchase_invoice
from erpnext.selling.doctype.sales_order.sales_order import make_purchase_order, make_sales_invoice
from erpnext.selling.doctype.sales_order.test_sales_order import make_sales_order
from erpnext.stock.doctype.item.test_item import make_item
item = make_item(
"_Test Drop Ship Consolidated Return Item",
properties={"is_stock_item": 1, "delivered_by_supplier": 1},
)
sales_orders = []
for qty, selling_rate, buying_rate in [(4, 100, 50), (6, 200, 80)]:
sales_order = make_sales_order(item=item.name, qty=qty, rate=selling_rate, do_not_submit=True)
sales_order.items[0].delivered_by_supplier = 1
sales_order.items[0].supplier = "_Test Supplier"
sales_order.submit()
sales_orders.append(sales_order)
purchase_order = make_purchase_order(sales_order.name, selected_items=[sales_order.items[0]])
purchase_order.items[0].rate = buying_rate
purchase_order.supplier = "_Test Supplier"
purchase_order.submit()
make_purchase_invoice(purchase_order.name).submit()
sales_invoice = make_sales_invoice(sales_orders[0].name)
sales_invoice = make_sales_invoice(sales_orders[1].name, target_doc=sales_invoice).submit()
sales_return = make_sales_return(sales_invoice.name)
sales_return.set("items", [sales_return.items[0]])
sales_return.items[0].qty = -1
sales_return.submit()
filters = frappe._dict(
company=sales_invoice.company,
from_date=sales_invoice.posting_date,
to_date=sales_invoice.posting_date,
group_by="Invoice",
)
_, data = execute(filters=filters)
invoice_rows = [row for row in data if row.parent_invoice == sales_invoice.name and row.indent == 1]
invoice_rows.sort(key=lambda row: row["avg._selling_rate"])
self.assertEqual([row.qty for row in invoice_rows], [3, 6])
self.assertEqual([row.buying_amount for row in invoice_rows], [150, 480])
def test_return_matches_sales_invoice_item_for_delivery_note(self):
make_stock_entry(
company=self.company,
item_code=self.item,
target=self.warehouse,
qty=4,
basic_rate=50,
)
delivery_note = self.create_delivery_note(qty=4, rate=100)
sales_invoice = make_sales_invoice(delivery_note.name).submit()
sales_return = make_sales_return(sales_invoice.name)
sales_return.items[0].qty = -1
sales_return.submit()
filters = frappe._dict(
company=sales_invoice.company,
from_date=sales_invoice.posting_date,
to_date=sales_invoice.posting_date,
group_by="Invoice",
)
_, data = execute(filters=filters)
invoice_row = next(
row for row in data if row.parent_invoice == sales_invoice.name and row.indent == 1
)
self.assertEqual(invoice_row.qty, 3)
self.assertEqual(invoice_row.selling_amount, 300)
def test_return_combines_linked_and_legacy_item_buckets(self):
sales_invoice = self.create_sales_invoice(qty=4, rate=100)
linked_return = make_sales_return(sales_invoice.name)
linked_return.items[0].qty = -1
linked_return.submit()
legacy_return = make_sales_return(sales_invoice.name)
legacy_return.items[0].qty = -1
legacy_return.submit()
frappe.db.set_value("Sales Invoice Item", legacy_return.items[0].name, "sales_invoice_item", None)
filters = frappe._dict(
company=sales_invoice.company,
from_date=sales_invoice.posting_date,
to_date=sales_invoice.posting_date,
group_by="Invoice",
)
_, data = execute(filters=filters)
invoice_row = next(
row for row in data if row.parent_invoice == sales_invoice.name and row.indent == 1
)
self.assertEqual(invoice_row.qty, 2)
self.assertEqual(invoice_row.selling_amount, 200)
@change_settings("Selling Settings", {"allow_multiple_items": True})
def test_legacy_return_prefers_item_without_linked_return(self):
sales_invoice = self.create_sales_invoice(qty=2, rate=100, do_not_submit=True)
second_item = frappe.copy_doc(sales_invoice.items[0], ignore_no_copy=False)
second_item.idx = None
second_item.rate = 200
sales_invoice.append("items", second_item)
sales_invoice.submit()
linked_return = make_sales_return(sales_invoice.name)
linked_return.set("items", [linked_return.items[0]])
linked_return.items[0].qty = -1
linked_return.submit()
legacy_return = make_sales_return(sales_invoice.name)
legacy_return.set("items", [legacy_return.items[1]])
legacy_return.items[0].qty = -1
legacy_return.submit()
frappe.db.set_value("Sales Invoice Item", legacy_return.items[0].name, "sales_invoice_item", None)
filters = frappe._dict(
company=sales_invoice.company,
from_date=sales_invoice.posting_date,
to_date=sales_invoice.posting_date,
group_by="Invoice",
)
_, data = execute(filters=filters)
invoice_rows = [row for row in data if row.parent_invoice == sales_invoice.name and row.indent == 1]
invoice_rows.sort(key=lambda row: row["avg._selling_rate"])
self.assertEqual([row.qty for row in invoice_rows], [1, 1])
self.assertEqual([row.selling_amount for row in invoice_rows], [100, 200])
def test_legacy_return_remainder_spills_into_linked_item(self):
invoice = "SINV-TEST-RETURN-ALLOCATION"
linked_item = "SINV-ITEM-LINKED"
unlinked_item = "SINV-ITEM-LEGACY"
generator = GrossProfitGenerator.__new__(GrossProfitGenerator)
generator.currency_precision = 3
generator.filters = frappe._dict(group_by="Invoice")
generator.returned_invoices = frappe._dict(
{invoice: frappe._dict({linked_item: [frappe._dict(qty=-1, base_amount=-100)]})}
)
generator.legacy_returned_invoices = frappe._dict(
{invoice: frappe._dict({self.item: [frappe._dict(qty=-2, base_amount=-200)]})}
)
linked_row = frappe._dict(
parent=invoice,
item_code=self.item,
item_row=linked_item,
is_return=False,
qty=3,
base_amount=300,
buying_rate=50,
delivered_by_supplier=False,
)
unlinked_row = frappe._dict(
parent=invoice,
item_code=self.item,
item_row=unlinked_item,
is_return=False,
qty=1,
base_amount=100,
buying_rate=50,
delivered_by_supplier=False,
)
generator.si_list = [unlinked_row, linked_row]
generator.allocate_legacy_return_items()
generator.update_return_invoices(linked_row, linked_item)
generator.update_return_invoices(unlinked_row, unlinked_item)
self.assertEqual((linked_row.qty, linked_row.base_amount), (1, 100))
self.assertEqual((unlinked_row.qty, unlinked_row.base_amount), (0, 0))
def test_legacy_return_ignores_skipped_group_rows(self):
invoice = "SINV-TEST-SKIPPED-RETURN-ALLOCATION"
visible_item = "SINV-ITEM-WITH-PROJECT"
skipped_item = "SINV-ITEM-WITHOUT-PROJECT"
generator = GrossProfitGenerator.__new__(GrossProfitGenerator)
generator.currency_precision = 3
generator.filters = frappe._dict(group_by="Project")
generator.returned_invoices = frappe._dict(
{invoice: frappe._dict({visible_item: [frappe._dict(qty=-1, base_amount=-100)]})}
)
generator.legacy_returned_invoices = frappe._dict(
{invoice: frappe._dict({self.item: [frappe._dict(qty=-1, base_amount=-100)]})}
)
visible_row = frappe._dict(
parent=invoice,
item_code=self.item,
item_row=visible_item,
is_return=False,
project="_Test Project",
qty=2,
base_amount=200,
buying_rate=50,
delivered_by_supplier=False,
)
skipped_row = frappe._dict(
parent=invoice,
item_code=self.item,
item_row=skipped_item,
is_return=False,
project=None,
qty=1,
)
generator.si_list = [visible_row, skipped_row]
generator.allocate_legacy_return_items()
generator.update_return_invoices(visible_row, visible_item)
self.assertNotIn(skipped_item, generator.returned_invoices[invoice])
self.assertEqual((visible_row.qty, visible_row.base_amount), (0, 0))
def test_monthly_group_allocates_legacy_return(self):
invoice = "SINV-TEST-MONTHLY-RETURN-ALLOCATION"
item_row = "SINV-ITEM-MONTHLY-RETURN"
generator = GrossProfitGenerator.__new__(GrossProfitGenerator)
generator.currency_precision = 3
generator.filters = frappe._dict(group_by="Monthly")
generator.returned_invoices = frappe._dict()
generator.legacy_returned_invoices = frappe._dict(
{invoice: frappe._dict({self.item: [frappe._dict(qty=-1, base_amount=-100)]})}
)
invoice_row = frappe._dict(
parent=invoice,
item_code=self.item,
item_row=item_row,
is_return=False,
posting_date=nowdate(),
qty=1,
base_amount=100,
buying_rate=50,
delivered_by_supplier=False,
)
generator.si_list = [invoice_row]
generator.allocate_legacy_return_items()
generator.update_return_invoices(invoice_row, item_row)
self.assertEqual((invoice_row.qty, invoice_row.base_amount), (0, 0))
def test_return_remainder_stays_available_for_next_row(self):
invoice = "SINV-TEST-RETURN-REMAINDER"
item_row = "SINV-ITEM-RETURN-REMAINDER"
returned_item = frappe._dict(qty=-2, base_amount=-200)
generator = GrossProfitGenerator.__new__(GrossProfitGenerator)
generator.currency_precision = 3
generator.returned_invoices = frappe._dict({invoice: frappe._dict({item_row: [returned_item]})})
first_row = frappe._dict(
parent=invoice,
item_code=self.item,
qty=1,
base_amount=100,
buying_rate=50,
delivered_by_supplier=False,
)
second_row = first_row.copy()
generator.update_return_invoices(first_row, item_row)
self.assertEqual((returned_item.qty, returned_item.base_amount), (-1, -100))
generator.update_return_invoices(second_row, item_row)
self.assertEqual((returned_item.qty, returned_item.base_amount), (0, 0))
self.assertEqual((first_row.qty, second_row.qty), (0, 0))
@change_settings("Selling Settings", {"allow_multiple_items": True})
def test_return_keeps_buying_amount_of_unreturned_row(self):
unreturned_item = create_item(
"_Test Gross Profit Unreturned Item", warehouse=self.warehouse, company=self.company
)
make_stock_entry(
company=self.company,
item_code=unreturned_item.name,
target=self.warehouse,
qty=40000,
basic_rate=33.33333,
)
sales_invoice = self.create_sales_invoice(qty=1, rate=100, do_not_submit=True)
second_item = frappe.copy_doc(sales_invoice.items[0], ignore_no_copy=False)
second_item.idx = None
second_item.item_code = unreturned_item.name
second_item.item_name = unreturned_item.name
second_item.qty = 30000
sales_invoice.append("items", second_item)
sales_invoice.submit()
sales_return = make_sales_return(sales_invoice.name)
sales_return.set("items", [sales_return.items[0]])
sales_return.items[0].qty = -1
sales_return.submit()
filters = frappe._dict(
company=sales_invoice.company,
from_date=sales_invoice.posting_date,
to_date=sales_invoice.posting_date,
group_by="Invoice",
)
_, data = execute(filters=filters)
invoice_row = next(
row
for row in data
if row.parent_invoice == sales_invoice.name and row.item_code == unreturned_item.name
)
self.assertEqual(invoice_row.qty, 30000)
self.assertEqual(invoice_row.buying_amount, 999999.9)
def create_drop_ship_order(self, qty=10, selling_rate=100, buying_rate=80):
from erpnext.buying.doctype.purchase_order.purchase_order import make_purchase_invoice
from erpnext.selling.doctype.sales_order.sales_order import make_purchase_order
from erpnext.selling.doctype.sales_order.test_sales_order import make_sales_order
from erpnext.stock.doctype.item.test_item import make_item
item = make_item("_Test Drop Ship Item", properties={"is_stock_item": 1, "delivered_by_supplier": 1})
so = make_sales_order(item=item.name, qty=qty, rate=selling_rate, do_not_submit=True)
so.items[0].delivered_by_supplier = 1
so.items[0].supplier = "_Test Supplier"
so.submit()
purchase_order = make_purchase_order(so.name, selected_items=[so.items[0]])
purchase_order.items[0].rate = buying_rate
purchase_order.supplier = "_Test Supplier"
purchase_order.submit()
make_purchase_invoice(purchase_order.name).submit()
return so
def make_sales_person(sales_person_name="_Test Sales Person"):
if not frappe.db.exists("Sales Person", {"sales_person_name": sales_person_name}):

View File

@@ -151,7 +151,13 @@ def _execute(filters, additional_table_columns=None):
)
if inv.doctype == "Sales Invoice":
row.update({"debit": inv.base_grand_total, "credit": 0.0})
# credit only settlements the invoice itself posts to the receivable (mirrors its GL)
row.update(
{
"debit": inv.base_grand_total,
"credit": get_in_invoice_receivable_credit(inv),
}
)
else:
row.update({"debit": 0.0, "credit": inv.base_grand_total})
data.append(row)
@@ -167,6 +173,14 @@ def _execute(filters, additional_table_columns=None):
return columns, res, None, None, None, include_payments
def get_in_invoice_receivable_credit(inv):
# amount the invoice settles against its own receivable, matching the invoice's GL entries
credit = flt(inv.loyalty_amount) # loyalty redemption, POS or not
if inv.is_pos: # POS payments and write-off credit the receivable only on POS invoices
credit += flt(inv.base_paid_amount) - flt(inv.base_change_amount) + flt(inv.base_write_off_amount)
return credit
def get_columns(invoice_list, additional_table_columns, include_payments=False):
"""return columns based on filters"""
columns = [
@@ -433,6 +447,11 @@ def get_invoices(filters, additional_query_columns):
si.base_net_total,
si.base_grand_total,
si.base_rounded_total,
si.is_pos,
si.base_paid_amount,
si.base_change_amount,
si.base_write_off_amount,
si.loyalty_amount,
si.outstanding_amount,
si.is_internal_customer,
si.represents_company,

View File

@@ -1,7 +1,8 @@
import frappe
from frappe.tests.utils import FrappeTestCase
from frappe.utils import getdate, today
from frappe.utils import flt, getdate, today
from erpnext.accounts.doctype.pos_profile.test_pos_profile import make_pos_profile
from erpnext.accounts.doctype.sales_invoice.test_sales_invoice import create_sales_invoice
from erpnext.accounts.report.sales_register.sales_register import execute
from erpnext.accounts.test.accounts_mixin import AccountsTestMixin
@@ -54,6 +55,46 @@ class TestItemWiseSalesRegister(AccountsTestMixin, FrappeTestCase):
si = si.submit()
return si
def test_ledger_view_nets_pos_paid_invoice(self):
# A POS payment settles the receivable inside the invoice, so the ledger view must credit it
# and net to zero instead of showing a phantom outstanding.
make_pos_profile()
si = create_sales_invoice(
item=self.item,
company=self.company,
customer=self.customer,
debit_to=self.debit_to,
posting_date=today(),
parent_cost_center=self.cost_center,
cost_center=self.cost_center,
rate=100,
price_list_rate=100,
do_not_save=1,
)
si.is_pos = 1
si.append("payments", {"mode_of_payment": "Cash", "amount": 100})
si = si.save().submit()
self.assertEqual(flt(si.outstanding_amount), 0.0)
filters = frappe._dict(
{
"from_date": today(),
"to_date": today(),
"company": self.company,
"include_payments": True,
"customer": self.customer,
}
)
rows = execute(filters)[1]
inv_row = next(x for x in rows if x.get("voucher_no") == si.name)
self.assertEqual(flt(inv_row.get("debit")), 100.0)
self.assertEqual(flt(inv_row.get("credit")), 100.0)
# running balance is unchanged by a fully-paid POS invoice
idx = rows.index(inv_row)
self.assertEqual(flt(inv_row.get("balance")), flt(rows[idx - 1].get("balance")))
def test_basic_report_output(self):
si = self.create_sales_invoice(rate=98)

View File

@@ -74,5 +74,27 @@ frappe.query_reports["Supplier Ledger Summary"] = {
fieldtype: "Data",
hidden: 1,
},
{
fieldname: "cost_center",
label: __("Cost Center"),
fieldtype: "MultiSelectList",
options: "Cost Center",
get_data: function (txt) {
return frappe.db.get_link_options("Cost Center", txt, {
company: frappe.query_report.get_filter_value("company"),
});
},
},
{
fieldname: "project",
label: __("Project"),
fieldtype: "MultiSelectList",
options: "Project",
get_data: function (txt) {
return frappe.db.get_link_options("Project", txt, {
company: frappe.query_report.get_filter_value("company"),
});
},
},
],
};

View File

@@ -7,6 +7,7 @@ from frappe import _
from frappe.utils import flt, getdate
from pypika import Tuple
from erpnext.accounts.report.utils import validate_mandatory_date_range
from erpnext.accounts.utils import get_currency_precision
@@ -33,9 +34,7 @@ def execute(filters=None):
def validate_filters(filters):
"""Validate if dates are properly set"""
filters = frappe._dict(filters or {})
if filters.from_date > filters.to_date:
frappe.throw(_("From Date must be before To Date"))
validate_mandatory_date_range(filters or {})
def get_result(filters, tds_accounts, tax_category_map, net_total_map):

View File

@@ -5,6 +5,7 @@ from erpnext.accounts.report.tax_withholding_details.tax_withholding_details imp
get_result,
get_tds_docs,
)
from erpnext.accounts.report.utils import validate_mandatory_date_range
from erpnext.accounts.utils import get_fiscal_year
@@ -33,8 +34,7 @@ def execute(filters=None):
def validate_filters(filters):
"""Validate if dates are properly set and lie in the same fiscal year"""
if filters.from_date > filters.to_date:
frappe.throw(_("From Date must be before To Date"))
validate_mandatory_date_range(filters)
from_year = get_fiscal_year(filters.from_date)[0]
to_year = get_fiscal_year(filters.to_date)[0]

View File

@@ -9,6 +9,7 @@ from frappe.utils import cint, flt
from erpnext.accounts.report.general_ledger.general_ledger import get_accounts_with_children
from erpnext.accounts.report.trial_balance.trial_balance import validate_filters
from erpnext.accounts.utils import get_currency_precision
def execute(filters=None):
@@ -43,6 +44,7 @@ def get_data(filters, show_party_name):
account_filter = get_accounts_with_children(filters.get("account"))
company_currency = frappe.get_cached_value("Company", filters.company, "default_currency")
precision = get_currency_precision()
opening_balances = get_opening_balances(filters, account_filter)
balances_within_period = get_balances_within_period(filters, account_filter)
@@ -65,14 +67,17 @@ def get_data(filters, show_party_name):
# opening
opening_debit, opening_credit = opening_balances.get(party.name, [0, 0])
opening_debit, opening_credit = flt(opening_debit, precision), flt(opening_credit, precision)
row.update({"opening_debit": opening_debit, "opening_credit": opening_credit})
# within period
debit, credit = balances_within_period.get(party.name, [0, 0])
debit, credit = flt(debit, precision), flt(credit, precision)
row.update({"debit": debit, "credit": credit})
# closing
closing_debit, closing_credit = toggle_debit_credit(opening_debit + debit, opening_credit + credit)
closing_debit, closing_credit = flt(closing_debit, precision), flt(closing_credit, precision)
row.update({"closing_debit": closing_debit, "closing_credit": closing_credit})
row.update({"currency": company_currency})

View File

@@ -1,4 +1,5 @@
import frappe
from frappe import _
from frappe.query_builder.custom import ConstantColumn
from frappe.query_builder.functions import Sum
from frappe.utils import flt, formatdate, get_datetime_str, get_table_name
@@ -16,6 +17,19 @@ from erpnext.setup.utils import get_exchange_rate
__exchange_rates = {}
def validate_mandatory_date_range(filters, from_field="from_date", to_field="to_date"):
from_date = filters.get(from_field)
to_date = filters.get(to_field)
if not from_date or not to_date:
frappe.throw(
_("{0} and {1} are mandatory").format(frappe.bold(_("From Date")), frappe.bold(_("To Date")))
)
if from_date > to_date:
frappe.throw(_("From Date must be before To Date"))
def get_currency(filters):
"""
Returns a dictionary containing currency information. The keys of the dict are
@@ -290,6 +304,9 @@ def get_payment_entries(filters, args):
pe.mode_of_payment,
pe.project,
pe.cost_center,
pe.payment_type,
pe.source_exchange_rate,
pe.target_exchange_rate,
)
.where(
(pe.docstatus == 1)
@@ -300,6 +317,22 @@ def get_payment_entries(filters, args):
)
query = apply_common_conditions(filters, query, doctype="Payment Entry", payments=True)
payment_entries = query.run(as_dict=True)
if payment_entries:
ded = frappe.qb.DocType("Payment Entry Deduction")
deduction_totals = frappe._dict(
frappe.qb.from_(ded)
.select(ded.parent, Sum(ded.amount))
.where(ded.parent.isin([d.name for d in payment_entries]) & (ded.is_exchange_gain_loss == 0))
.groupby(ded.parent)
.run()
)
for d in payment_entries:
exchange_rate = (
d.source_exchange_rate if d.payment_type == "Receive" else d.target_exchange_rate
) or 1
d.base_grand_total = flt(d.base_grand_total) + flt(deduction_totals.get(d.name)) / exchange_rate
return payment_entries

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