Skip to content

Commit fbf4305

Browse files
Matt Howardmergify[bot]
authored andcommitted
fix(postgres): compute current month sales without DATE_FORMAT
(cherry picked from commit 64f391a)
1 parent eef26fe commit fbf4305

1 file changed

Lines changed: 42 additions & 23 deletions

File tree

erpnext/setup/doctype/company/company.py

Lines changed: 42 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,16 @@
1111
from frappe.contacts.address_and_contact import load_address_and_contact
1212
from frappe.custom.doctype.property_setter.property_setter import make_property_setter
1313
from frappe.desk.page.setup_wizard.setup_wizard import make_records
14-
from frappe.utils import add_months, cint, formatdate, get_first_day, get_link_to_form, get_timestamp, today
14+
from frappe.utils import (
15+
add_months,
16+
cint,
17+
formatdate,
18+
get_first_day,
19+
get_last_day,
20+
get_link_to_form,
21+
get_timestamp,
22+
today,
23+
)
1524
from frappe.utils.nestedset import NestedSet, rebuild_tree
1625

1726
from erpnext.accounts.doctype.account.account import get_account_currency
@@ -762,30 +771,40 @@ def install_country_fixtures(company, country):
762771

763772

764773
def update_company_current_month_sales(company):
765-
from_date = get_first_day(today())
766-
to_date = get_first_day(add_months(from_date, 1))
774+
"""Update Company's Total Monthly Sales.
767775
768-
results = frappe.db.sql(
769-
"""
770-
SELECT
771-
SUM(base_grand_total) AS total,
772-
DATE_FORMAT(posting_date, '%%m-%%Y') AS month_year
773-
FROM
774-
`tabSales Invoice`
775-
WHERE
776-
posting_date >= %s
777-
AND posting_date < %s
778-
AND docstatus = 1
779-
AND company = %s
780-
GROUP BY
781-
month_year
782-
""",
783-
(from_date, to_date, company),
784-
as_dict=True,
785-
)
776+
Postgres compatibility:
777+
- Avoid MariaDB-only DATE_FORMAT().
778+
- Use a date range for the current month instead (portable + index-friendly).
779+
"""
786780

787-
monthly_total = results[0]["total"] if len(results) > 0 else 0
788-
frappe.db.set_value("Company", company, "total_monthly_sales", monthly_total)
781+
# Local imports so you don't have to touch file-level imports
782+
from frappe.query_builder.functions import Sum
783+
784+
start_date = get_first_day(today())
785+
end_date = get_last_day(today())
786+
787+
si = frappe.qb.DocType("Sales Invoice")
788+
789+
total_monthly_sales = (
790+
frappe.qb.from_(si)
791+
.select(Sum(si.base_grand_total))
792+
.where(
793+
(si.docstatus == 1)
794+
& (si.company == company)
795+
& (si.posting_date >= start_date)
796+
& (si.posting_date <= end_date)
797+
)
798+
).run(pluck=True)[0] or 0
799+
800+
# Fieldname in standard ERPNext is `total_monthly_sales`
801+
frappe.db.set_value(
802+
"Company",
803+
company,
804+
"total_monthly_sales",
805+
total_monthly_sales,
806+
update_modified=False,
807+
)
789808

790809

791810
def update_company_monthly_sales(company):

0 commit comments

Comments
 (0)