blob: b17c72d0bd1e51e94b32f41f7d86fb10e1435b9f [file] [log] [blame]
Anand Doshi885e0742015-03-03 14:55:30 +05301# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
Rushabh Mehtae67d1fb2013-08-05 14:59:54 +05302# License: GNU General Public License v3. See license.txt
Saurabh02875592013-07-08 18:45:55 +05303
Chillar Anand915b3432021-09-02 16:44:59 +05304
rohitwaghchaurec59371a2021-06-03 20:02:58 +05305import json
Rohit Waghchaureacd12c52023-06-04 16:09:01 +05306from collections import OrderedDict, defaultdict
Chillar Anand915b3432021-09-02 16:44:59 +05307
8import frappe
ruthra kumar4eefb442024-01-16 13:38:53 +05309from frappe import qb, scrub
Chillar Anand915b3432021-09-02 16:44:59 +053010from frappe.desk.reportview import get_filters_cond, get_match_cond
ruthra kumarbfe42fd2024-01-16 14:35:06 +053011from frappe.query_builder import Criterion, CustomFunction
12from frappe.query_builder.functions import Concat, Locate, Sum
Rohit Waghchaureacd12c52023-06-04 16:09:01 +053013from frappe.utils import nowdate, today, unique
ruthra kumarbfe42fd2024-01-16 14:35:06 +053014from pypika import Order
Chillar Anand915b3432021-09-02 16:44:59 +053015
16import erpnext
Deepesh Gargef0d26c2020-01-06 15:34:15 +053017from erpnext.stock.get_item_details import _get_item_tax_template
Chillar Anand915b3432021-09-02 16:44:59 +053018
Saurabh02875592013-07-08 18:45:55 +053019
Chinmay D. Paiaa121092020-07-01 21:14:32 +053020# searches for active employees
21@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +053022@frappe.validate_and_sanitize_search_inputs
Saurabh02875592013-07-08 18:45:55 +053023def employee_query(doctype, txt, searchfield, start, page_len, filters):
Sagar Vora9baa2222022-08-03 05:42:30 +000024 doctype = "Employee"
Kanchan Chauhan7652b852016-11-16 15:29:01 +053025 conditions = []
Sagar Vora9baa2222022-08-03 05:42:30 +000026 fields = get_fields(doctype, ["name", "employee_name"])
Himanshud94a38e2020-05-18 14:26:26 +053027
Ankush Menat494bd9e2022-03-28 18:52:46 +053028 return frappe.db.sql(
29 """select {fields} from `tabEmployee`
Anurag Mishrafc98abe2021-06-23 11:21:38 +053030 where status in ('Active', 'Suspended')
Anand Doshibd67e872014-04-11 16:51:27 +053031 and docstatus < 2
Anand Doshi48d3b542014-07-09 13:15:03 +053032 and ({key} like %(txt)s
33 or employee_name like %(txt)s)
Kanchan Chauhan7652b852016-11-16 15:29:01 +053034 {fcond} {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +053035 order by
Conorea28ed12022-06-17 10:47:48 -050036 (case when locate(%(_txt)s, name) > 0 then locate(%(_txt)s, name) else 99999 end),
37 (case when locate(%(_txt)s, employee_name) > 0 then locate(%(_txt)s, employee_name) else 99999 end),
Rushabh Mehta3574b372016-03-11 14:33:04 +053038 idx desc,
Anand Doshi652bc072014-04-16 15:21:46 +053039 name, employee_name
Conor00ef4992022-06-14 00:19:07 -050040 limit %(page_len)s offset %(start)s""".format(
Ankush Menat494bd9e2022-03-28 18:52:46 +053041 **{
42 "fields": ", ".join(fields),
43 "key": searchfield,
44 "fcond": get_filters_cond(doctype, filters, conditions),
45 "mcond": get_match_cond(doctype),
46 }
47 ),
48 {"txt": "%%%s%%" % txt, "_txt": txt.replace("%", ""), "start": start, "page_len": page_len},
49 )
Saurabh02875592013-07-08 18:45:55 +053050
Himanshud94a38e2020-05-18 14:26:26 +053051
52# searches for leads which are not converted
Chinmay D. Paiaa121092020-07-01 21:14:32 +053053@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +053054@frappe.validate_and_sanitize_search_inputs
Anand Doshibd67e872014-04-11 16:51:27 +053055def lead_query(doctype, txt, searchfield, start, page_len, filters):
Sagar Vora9baa2222022-08-03 05:42:30 +000056 doctype = "Lead"
57 fields = get_fields(doctype, ["name", "lead_name", "company_name"])
Himanshud94a38e2020-05-18 14:26:26 +053058
HarryPauloe12e3bb2023-05-13 23:38:47 -030059 searchfields = frappe.get_meta(doctype).get_search_fields()
60 searchfields = " or ".join(field + " like %(txt)s" for field in searchfields)
61
Ankush Menat494bd9e2022-03-28 18:52:46 +053062 return frappe.db.sql(
63 """select {fields} from `tabLead`
Anand Doshibd67e872014-04-11 16:51:27 +053064 where docstatus < 2
65 and ifnull(status, '') != 'Converted'
Anand Doshi48d3b542014-07-09 13:15:03 +053066 and ({key} like %(txt)s
67 or lead_name like %(txt)s
HarryPauloe12e3bb2023-05-13 23:38:47 -030068 or company_name like %(txt)s
69 or {scond})
Anand Doshi48d3b542014-07-09 13:15:03 +053070 {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +053071 order by
Conorea28ed12022-06-17 10:47:48 -050072 (case when locate(%(_txt)s, name) > 0 then locate(%(_txt)s, name) else 99999 end),
73 (case when locate(%(_txt)s, lead_name) > 0 then locate(%(_txt)s, lead_name) else 99999 end),
74 (case when locate(%(_txt)s, company_name) > 0 then locate(%(_txt)s, company_name) else 99999 end),
Rushabh Mehta3574b372016-03-11 14:33:04 +053075 idx desc,
Anand Doshi652bc072014-04-16 15:21:46 +053076 name, lead_name
Conor00ef4992022-06-14 00:19:07 -050077 limit %(page_len)s offset %(start)s""".format(
HarryPauloe12e3bb2023-05-13 23:38:47 -030078 **{
79 "fields": ", ".join(fields),
80 "key": searchfield,
81 "scond": searchfields,
82 "mcond": get_match_cond(doctype),
83 }
Ankush Menat494bd9e2022-03-28 18:52:46 +053084 ),
85 {"txt": "%%%s%%" % txt, "_txt": txt.replace("%", ""), "start": start, "page_len": page_len},
86 )
87
88 # searches for customer
Saurabh02875592013-07-08 18:45:55 +053089
Himanshud94a38e2020-05-18 14:26:26 +053090
Chinmay D. Paiaa121092020-07-01 21:14:32 +053091@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +053092@frappe.validate_and_sanitize_search_inputs
Rohit Waghchaure5f849932022-10-24 16:10:47 +053093def customer_query(doctype, txt, searchfield, start, page_len, filters, as_dict=False):
Sagar Vora9baa2222022-08-03 05:42:30 +000094 doctype = "Customer"
KanchanChauhan4b888b92017-07-25 14:03:01 +053095 conditions = []
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053096 cust_master_name = frappe.defaults.get_user_default("cust_master_name")
Saurabhf52dc072013-07-10 13:07:49 +053097
Rohit Waghchaure46d148d2022-10-24 15:48:34 +053098 fields = ["name"]
99 if cust_master_name != "Customer Name":
Rohit Waghchaureb0fc5682022-11-03 11:24:58 +0530100 fields.append("customer_name")
Rushabh Mehtab92087c2017-01-13 18:53:11 +0530101
Sagar Vora9baa2222022-08-03 05:42:30 +0000102 fields = get_fields(doctype, fields)
Sagar Vora9baa2222022-08-03 05:42:30 +0000103 searchfields = frappe.get_meta(doctype).get_search_fields()
Ankush Menata9c84f72021-06-11 16:00:48 +0530104 searchfields = " or ".join(field + " like %(txt)s" for field in searchfields)
Saurabh02875592013-07-08 18:45:55 +0530105
Ankush Menat494bd9e2022-03-28 18:52:46 +0530106 return frappe.db.sql(
107 """select {fields} from `tabCustomer`
Anand Doshibd67e872014-04-11 16:51:27 +0530108 where docstatus < 2
Console Admin86231662017-06-23 20:32:52 +0300109 and ({scond}) and disabled=0
KanchanChauhan4b888b92017-07-25 14:03:01 +0530110 {fcond} {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +0530111 order by
Conorea28ed12022-06-17 10:47:48 -0500112 (case when locate(%(_txt)s, name) > 0 then locate(%(_txt)s, name) else 99999 end),
113 (case when locate(%(_txt)s, customer_name) > 0 then locate(%(_txt)s, customer_name) else 99999 end),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530114 idx desc,
Anand Doshibd67e872014-04-11 16:51:27 +0530115 name, customer_name
Conor00ef4992022-06-14 00:19:07 -0500116 limit %(page_len)s offset %(start)s""".format(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530117 **{
118 "fields": ", ".join(fields),
119 "scond": searchfields,
120 "mcond": get_match_cond(doctype),
121 "fcond": get_filters_cond(doctype, filters, conditions).replace("%", "%%"),
122 }
123 ),
124 {"txt": "%%%s%%" % txt, "_txt": txt.replace("%", ""), "start": start, "page_len": page_len},
Rohit Waghchaure5f849932022-10-24 16:10:47 +0530125 as_dict=as_dict,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530126 )
Saurabh02875592013-07-08 18:45:55 +0530127
Himanshud94a38e2020-05-18 14:26:26 +0530128
Saurabh02875592013-07-08 18:45:55 +0530129# searches for supplier
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530130@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530131@frappe.validate_and_sanitize_search_inputs
Rohit Waghchaure5f849932022-10-24 16:10:47 +0530132def supplier_query(doctype, txt, searchfield, start, page_len, filters, as_dict=False):
Sagar Vora9baa2222022-08-03 05:42:30 +0000133 doctype = "Supplier"
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530134 supp_master_name = frappe.defaults.get_user_default("supp_master_name")
Suraj Shetty1923ef02020-08-05 19:42:25 +0530135
Rohit Waghchaure46d148d2022-10-24 15:48:34 +0530136 fields = ["name"]
137 if supp_master_name != "Supplier Name":
Rohit Waghchaureb0fc5682022-11-03 11:24:58 +0530138 fields.append("supplier_name")
Himanshud94a38e2020-05-18 14:26:26 +0530139
Sagar Vora9baa2222022-08-03 05:42:30 +0000140 fields = get_fields(doctype, fields)
Saurabh02875592013-07-08 18:45:55 +0530141
Ankush Menat494bd9e2022-03-28 18:52:46 +0530142 return frappe.db.sql(
143 """select {field} from `tabSupplier`
Anand Doshibd67e872014-04-11 16:51:27 +0530144 where docstatus < 2
Anand Doshi48d3b542014-07-09 13:15:03 +0530145 and ({key} like %(txt)s
Ankush Menat2221c9e2021-10-27 19:15:44 +0530146 or supplier_name like %(txt)s) and disabled=0
Conorea28ed12022-06-17 10:47:48 -0500147 and (on_hold = 0 or (on_hold = 1 and CURRENT_DATE > release_date))
Anand Doshi48d3b542014-07-09 13:15:03 +0530148 {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +0530149 order by
Conorea28ed12022-06-17 10:47:48 -0500150 (case when locate(%(_txt)s, name) > 0 then locate(%(_txt)s, name) else 99999 end),
151 (case when locate(%(_txt)s, supplier_name) > 0 then locate(%(_txt)s, supplier_name) else 99999 end),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530152 idx desc,
Anand Doshibd67e872014-04-11 16:51:27 +0530153 name, supplier_name
Conor00ef4992022-06-14 00:19:07 -0500154 limit %(page_len)s offset %(start)s""".format(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530155 **{"field": ", ".join(fields), "key": searchfield, "mcond": get_match_cond(doctype)}
156 ),
157 {"txt": "%%%s%%" % txt, "_txt": txt.replace("%", ""), "start": start, "page_len": page_len},
Rohit Waghchaure5f849932022-10-24 16:10:47 +0530158 as_dict=as_dict,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530159 )
Anand Doshibd67e872014-04-11 16:51:27 +0530160
Himanshud94a38e2020-05-18 14:26:26 +0530161
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530162@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530163@frappe.validate_and_sanitize_search_inputs
Nabin Hait9a380ef2013-07-16 17:24:17 +0530164def tax_account_query(doctype, txt, searchfield, start, page_len, filters):
Sagar Vora9baa2222022-08-03 05:42:30 +0000165 doctype = "Account"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530166 company_currency = erpnext.get_company_currency(filters.get("company"))
Deepesh Gargfbf6e562020-03-31 10:45:32 +0530167
Suraj Shetty1923ef02020-08-05 19:42:25 +0530168 def get_accounts(with_account_type_filter):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530169 account_type_condition = ""
Suraj Shetty1923ef02020-08-05 19:42:25 +0530170 if with_account_type_filter:
171 account_type_condition = "AND account_type in %(account_types)s"
172
Ankush Menat494bd9e2022-03-28 18:52:46 +0530173 accounts = frappe.db.sql(
174 """
Suraj Shetty1923ef02020-08-05 19:42:25 +0530175 SELECT name, parent_account
176 FROM `tabAccount`
177 WHERE `tabAccount`.docstatus!=2
178 {account_type_condition}
179 AND is_group = 0
180 AND company = %(company)s
Saqib Ansaria1e3ae82022-05-11 13:01:06 +0530181 AND disabled = %(disabled)s
Deepesh Garg57924592022-03-22 18:26:58 +0530182 AND (account_currency = %(currency)s or ifnull(account_currency, '') = '')
Suraj Shetty1923ef02020-08-05 19:42:25 +0530183 AND `{searchfield}` LIKE %(txt)s
prssannade7a2bc2020-09-21 13:57:04 +0530184 {mcond}
Suraj Shetty1923ef02020-08-05 19:42:25 +0530185 ORDER BY idx DESC, name
Conor00ef4992022-06-14 00:19:07 -0500186 LIMIT %(limit)s offset %(offset)s
prssannade7a2bc2020-09-21 13:57:04 +0530187 """.format(
188 account_type_condition=account_type_condition,
189 searchfield=searchfield,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530190 mcond=get_match_cond(doctype),
prssannade7a2bc2020-09-21 13:57:04 +0530191 ),
Suraj Shetty1923ef02020-08-05 19:42:25 +0530192 dict(
193 account_types=filters.get("account_type"),
194 company=filters.get("company"),
Saqib Ansaria1e3ae82022-05-11 13:01:06 +0530195 disabled=filters.get("disabled", 0),
Suraj Shetty1923ef02020-08-05 19:42:25 +0530196 currency=company_currency,
197 txt="%{}%".format(txt),
198 offset=start,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530199 limit=page_len,
200 ),
Suraj Shetty1923ef02020-08-05 19:42:25 +0530201 )
202
203 return accounts
204
205 tax_accounts = get_accounts(True)
206
Nabin Hait0c21e2a2014-03-21 11:14:49 +0530207 if not tax_accounts:
Suraj Shetty1923ef02020-08-05 19:42:25 +0530208 tax_accounts = get_accounts(False)
Anand Doshibd67e872014-04-11 16:51:27 +0530209
Nabin Hait0c21e2a2014-03-21 11:14:49 +0530210 return tax_accounts
Saurabh02875592013-07-08 18:45:55 +0530211
Himanshud94a38e2020-05-18 14:26:26 +0530212
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530213@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530214@frappe.validate_and_sanitize_search_inputs
Rushabh Mehta203cc962016-04-07 15:25:43 +0530215def item_query(doctype, txt, searchfield, start, page_len, filters, as_dict=False):
Sagar Vora9baa2222022-08-03 05:42:30 +0000216 doctype = "Item"
Saurabh02875592013-07-08 18:45:55 +0530217 conditions = []
Saurabhf52dc072013-07-10 13:07:49 +0530218
rohitwaghchaurec59371a2021-06-03 20:02:58 +0530219 if isinstance(filters, str):
220 filters = json.loads(filters)
221
Ankush Menat494bd9e2022-03-28 18:52:46 +0530222 # Get searchfields from meta and use in Item Link field query
Sagar Vora9baa2222022-08-03 05:42:30 +0000223 meta = frappe.get_meta(doctype, cached=True)
marination3dbef9d2019-10-28 15:48:10 +0530224 searchfields = meta.get_search_fields()
225
Ankush Menat494bd9e2022-03-28 18:52:46 +0530226 columns = ""
barredterraeb9ee3f2023-12-05 11:22:55 +0100227 extra_searchfields = [field for field in searchfields if field not in ["name", "description"]]
Rohit Waghchaurec42312e2019-11-19 19:05:23 +0530228
229 if extra_searchfields:
Rohit Waghchaurefd889fd2022-09-28 23:00:45 +0530230 columns += ", " + ", ".join(extra_searchfields)
231
232 if "description" in searchfields:
233 columns += """, if(length(tabItem.description) > 40, \
234 concat(substr(tabItem.description, 1, 40), "..."), description) as description"""
marination1e754b12019-10-30 18:33:44 +0530235
Ankush Menat494bd9e2022-03-28 18:52:46 +0530236 searchfields = searchfields + [
237 field
barredterraeb9ee3f2023-12-05 11:22:55 +0100238 for field in [
239 searchfield or "name",
240 "item_code",
241 "item_group",
242 "item_name",
243 ]
244 if field not in searchfields
Ankush Menat494bd9e2022-03-28 18:52:46 +0530245 ]
marination3dbef9d2019-10-28 15:48:10 +0530246 searchfields = " or ".join([field + " like %(txt)s" for field in searchfields])
247
DeeMysterioaa826242021-09-14 13:58:18 +0530248 if filters and isinstance(filters, dict):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530249 if filters.get("customer") or filters.get("supplier"):
250 party = filters.get("customer") or filters.get("supplier")
251 item_rules_list = frappe.get_all(
252 "Party Specific Item", filters={"party": party}, fields=["restrict_based_on", "based_on_value"]
253 )
Rohit Waghchaure721b4132021-06-02 14:13:09 +0530254
DeeMysterioaa826242021-09-14 13:58:18 +0530255 filters_dict = {}
256 for rule in item_rules_list:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530257 if rule["restrict_based_on"] == "Item":
258 rule["restrict_based_on"] = "name"
DeeMysterioaa826242021-09-14 13:58:18 +0530259 filters_dict[rule.restrict_based_on] = []
noahjacobca2fb472021-05-12 16:25:07 +0530260
DeeMysterioaa826242021-09-14 13:58:18 +0530261 for rule in item_rules_list:
262 filters_dict[rule.restrict_based_on].append(rule.based_on_value)
noahjacobca2fb472021-05-12 16:25:07 +0530263
DeeMysterioaa826242021-09-14 13:58:18 +0530264 for filter in filters_dict:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530265 filters[scrub(filter)] = ["in", filters_dict[filter]]
DeeMysterioaa826242021-09-14 13:58:18 +0530266
Ankush Menat494bd9e2022-03-28 18:52:46 +0530267 if filters.get("customer"):
268 del filters["customer"]
DeeMysterioaa826242021-09-14 13:58:18 +0530269 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530270 del filters["supplier"]
Ankush Menat41a95e52022-02-03 13:02:13 +0530271 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530272 filters.pop("customer", None)
273 filters.pop("supplier", None)
DeeMysterioaa826242021-09-14 13:58:18 +0530274
Ankush Menat494bd9e2022-03-28 18:52:46 +0530275 description_cond = ""
Sagar Vora9baa2222022-08-03 05:42:30 +0000276 if frappe.db.count(doctype, cache=True) < 50000:
Rushabh Mehtad5f9ebd2018-04-02 23:37:33 +0530277 # scan description only if items are less than 50000
Ankush Menat494bd9e2022-03-28 18:52:46 +0530278 description_cond = "or tabItem.description LIKE %(txt)s"
Rohit Waghchaurefd889fd2022-09-28 23:00:45 +0530279
Ankush Menat494bd9e2022-03-28 18:52:46 +0530280 return frappe.db.sql(
281 """select
Rohit Waghchaurefd889fd2022-09-28 23:00:45 +0530282 tabItem.name {columns}
Anand Doshibd67e872014-04-11 16:51:27 +0530283 from tabItem
Anand Doshi22c0d782013-11-04 16:23:04 +0530284 where tabItem.docstatus < 2
Anand Doshi21e09a22015-10-29 12:21:41 +0530285 and tabItem.disabled=0
rohitwaghchaure79789072020-05-21 18:10:13 +0530286 and tabItem.has_variants=0
Rushabh Mehta864d1ea2014-06-23 12:20:12 +0530287 and (tabItem.end_of_life > %(today)s or ifnull(tabItem.end_of_life, '0000-00-00')='0000-00-00')
marination3dbef9d2019-10-28 15:48:10 +0530288 and ({scond} or tabItem.item_code IN (select parent from `tabItem Barcode` where barcode LIKE %(txt)s)
Rohit Waghchaure2bfb0632019-03-02 21:47:55 +0530289 {description_cond})
Anand Doshi22c0d782013-11-04 16:23:04 +0530290 {fcond} {mcond}
Anand Doshi652bc072014-04-16 15:21:46 +0530291 order by
292 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
293 if(locate(%(_txt)s, item_name), locate(%(_txt)s, item_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530294 idx desc,
Anand Doshi652bc072014-04-16 15:21:46 +0530295 name, item_name
Rushabh Mehtabc4e2cd2017-10-17 12:30:34 +0530296 limit %(start)s, %(page_len)s """.format(
marination1e754b12019-10-30 18:33:44 +0530297 columns=columns,
marination3dbef9d2019-10-28 15:48:10 +0530298 scond=searchfields,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530299 fcond=get_filters_cond(doctype, filters, conditions).replace("%", "%%"),
300 mcond=get_match_cond(doctype).replace("%", "%%"),
301 description_cond=description_cond,
302 ),
303 {
304 "today": nowdate(),
305 "txt": "%%%s%%" % txt,
306 "_txt": txt.replace("%", ""),
307 "start": start,
308 "page_len": page_len,
309 },
310 as_dict=as_dict,
311 )
Saurabh02875592013-07-08 18:45:55 +0530312
Himanshud94a38e2020-05-18 14:26:26 +0530313
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530314@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530315@frappe.validate_and_sanitize_search_inputs
Saurabh022ab632017-11-10 15:06:02 +0530316def bom(doctype, txt, searchfield, start, page_len, filters):
Sagar Vora9baa2222022-08-03 05:42:30 +0000317 doctype = "BOM"
Anand Doshibd67e872014-04-11 16:51:27 +0530318 conditions = []
Sagar Vora9baa2222022-08-03 05:42:30 +0000319 fields = get_fields(doctype, ["name", "item"])
Saurabhf52dc072013-07-10 13:07:49 +0530320
Ankush Menat494bd9e2022-03-28 18:52:46 +0530321 return frappe.db.sql(
322 """select {fields}
Conorea28ed12022-06-17 10:47:48 -0500323 from `tabBOM`
324 where `tabBOM`.docstatus=1
325 and `tabBOM`.is_active=1
326 and `tabBOM`.`{key}` like %(txt)s
Nabin Hait62211172016-03-16 16:22:03 +0530327 {fcond} {mcond}
328 order by
Conorea28ed12022-06-17 10:47:48 -0500329 (case when locate(%(_txt)s, name) > 0 then locate(%(_txt)s, name) else 99999 end),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530330 idx desc, name
Conorea28ed12022-06-17 10:47:48 -0500331 limit %(page_len)s offset %(start)s""".format(
Himanshud94a38e2020-05-18 14:26:26 +0530332 fields=", ".join(fields),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530333 fcond=get_filters_cond(doctype, filters, conditions).replace("%", "%%"),
334 mcond=get_match_cond(doctype).replace("%", "%%"),
335 key=searchfield,
336 ),
Mangesh-Khairnar6a796912019-07-08 10:40:40 +0530337 {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530338 "txt": "%" + txt + "%",
339 "_txt": txt.replace("%", ""),
340 "start": start or 0,
341 "page_len": page_len or 20,
342 },
343 )
Saurabh02875592013-07-08 18:45:55 +0530344
Himanshud94a38e2020-05-18 14:26:26 +0530345
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530346@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530347@frappe.validate_and_sanitize_search_inputs
Saurabh02875592013-07-08 18:45:55 +0530348def get_project_name(doctype, txt, searchfield, start, page_len, filters):
ruthra kumar4eefb442024-01-16 13:38:53 +0530349 proj = qb.DocType("Project")
350 qb_filter_and_conditions = []
351 qb_filter_or_conditions = []
ruthra kumarbfe42fd2024-01-16 14:35:06 +0530352 ifelse = CustomFunction("IF", ["condition", "then", "else"])
353
Ankush Menat494bd9e2022-03-28 18:52:46 +0530354 if filters and filters.get("customer"):
Deepesh Gargd0e0b662024-03-07 09:14:56 +0530355 qb_filter_and_conditions.append(
356 (proj.customer == filters.get("customer")) | proj.customer.isnull() | proj.customer == ""
357 )
Anand Doshibd67e872014-04-11 16:51:27 +0530358
ruthra kumar4eefb442024-01-16 13:38:53 +0530359 qb_filter_and_conditions.append(proj.status.notin(["Completed", "Cancelled"]))
Himanshud94a38e2020-05-18 14:26:26 +0530360
ruthra kumar4eefb442024-01-16 13:38:53 +0530361 q = qb.from_(proj)
362
ruthra kumar3349dde2024-01-16 14:28:09 +0530363 fields = get_fields(doctype, ["name", "project_name"])
ruthra kumar4eefb442024-01-16 13:38:53 +0530364 for x in fields:
365 q = q.select(proj[x])
366
ruthra kumarbfe42fd2024-01-16 14:35:06 +0530367 # don't consider 'customer' and 'status' fields for pattern search, as they must be exactly matched
ruthra kumar4eefb442024-01-16 13:38:53 +0530368 searchfields = [
369 x for x in frappe.get_meta(doctype).get_search_fields() if x not in ["customer", "status"]
370 ]
ruthra kumarbfe42fd2024-01-16 14:35:06 +0530371
372 # pattern search
ruthra kumar4eefb442024-01-16 13:38:53 +0530373 if txt:
374 for x in searchfields:
375 qb_filter_or_conditions.append(proj[x].like(f"%{txt}%"))
376
377 q = q.where(Criterion.all(qb_filter_and_conditions)).where(Criterion.any(qb_filter_or_conditions))
ruthra kumarbfe42fd2024-01-16 14:35:06 +0530378
379 # ordering
380 if txt:
381 # project_name containing search string 'txt' will be given higher precedence
382 q = q.orderby(ifelse(Locate(txt, proj.project_name) > 0, Locate(txt, proj.project_name), 99999))
383 q = q.orderby(proj.idx, order=Order.desc).orderby(proj.name)
384
ruthra kumar4eefb442024-01-16 13:38:53 +0530385 if page_len:
386 q = q.limit(page_len)
ruthra kumarbfe42fd2024-01-16 14:35:06 +0530387
388 if start:
389 q = q.offset(start)
ruthra kumar4eefb442024-01-16 13:38:53 +0530390 return q.run()
Anand Doshibd67e872014-04-11 16:51:27 +0530391
tundebabzyf6d738b2017-09-18 12:40:09 +0100392
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530393@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530394@frappe.validate_and_sanitize_search_inputs
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530395def get_delivery_notes_to_be_billed(doctype, txt, searchfield, start, page_len, filters, as_dict):
Sagar Vora9baa2222022-08-03 05:42:30 +0000396 doctype = "Delivery Note"
397 fields = get_fields(doctype, ["name", "customer", "posting_date"])
Himanshud94a38e2020-05-18 14:26:26 +0530398
Ankush Menat494bd9e2022-03-28 18:52:46 +0530399 return frappe.db.sql(
400 """
Himanshud94a38e2020-05-18 14:26:26 +0530401 select %(fields)s
Anand Doshibd67e872014-04-11 16:51:27 +0530402 from `tabDelivery Note`
403 where `tabDelivery Note`.`%(key)s` like %(txt)s and
tundebabzyf6d738b2017-09-18 12:40:09 +0100404 `tabDelivery Note`.docstatus = 1
Conor74a782d2022-06-17 06:31:27 -0500405 and status not in ('Stopped', 'Closed') %(fcond)s
tundebabzyf6d738b2017-09-18 12:40:09 +0100406 and (
407 (`tabDelivery Note`.is_return = 0 and `tabDelivery Note`.per_billed < 100)
Deepesh Garge2dc1022021-04-14 11:21:11 +0530408 or (`tabDelivery Note`.grand_total = 0 and `tabDelivery Note`.per_billed < 100)
tundebabzyf6d738b2017-09-18 12:40:09 +0100409 or (
410 `tabDelivery Note`.is_return = 1
411 and return_against in (select name from `tabDelivery Note` where per_billed < 100)
412 )
413 )
Conor00ef4992022-06-14 00:19:07 -0500414 %(mcond)s order by `tabDelivery Note`.`%(key)s` asc limit %(page_len)s offset %(start)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530415 """
416 % {
417 "fields": ", ".join(["`tabDelivery Note`.{0}".format(f) for f in fields]),
418 "key": searchfield,
419 "fcond": get_filters_cond(doctype, filters, []),
420 "mcond": get_match_cond(doctype),
421 "start": start,
422 "page_len": page_len,
423 "txt": "%(txt)s",
424 },
425 {"txt": ("%%%s%%" % txt)},
426 as_dict=as_dict,
427 )
tundebabzyf6d738b2017-09-18 12:40:09 +0100428
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530429
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530430@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530431@frappe.validate_and_sanitize_search_inputs
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530432def get_batch_no(doctype, txt, searchfield, start, page_len, filters):
Sagar Vora9baa2222022-08-03 05:42:30 +0000433 doctype = "Batch"
Sagar Vora9baa2222022-08-03 05:42:30 +0000434 meta = frappe.get_meta(doctype, cached=True)
Deepesh Garga0d192e2020-09-22 13:54:07 +0530435 searchfields = meta.get_search_fields()
436
Rohit Waghchaure114f2b42024-01-14 23:23:55 +0530437 batches = get_batches_from_stock_ledger_entries(searchfields, txt, filters, start, page_len)
438 batches.extend(
439 get_batches_from_serial_and_batch_bundle(searchfields, txt, filters, start, page_len)
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530440 )
Deepesh Garga0d192e2020-09-22 13:54:07 +0530441
Rohit Waghchaure114f2b42024-01-14 23:23:55 +0530442 filtered_batches = get_filterd_batches(batches)
Deepesh Garga0d192e2020-09-22 13:54:07 +0530443
Rohit Waghchaure114f2b42024-01-14 23:23:55 +0530444 return filtered_batches
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530445
446
447def get_filterd_batches(data):
448 batches = OrderedDict()
449
450 for batch_data in data:
451 if batch_data[0] not in batches:
452 batches[batch_data[0]] = list(batch_data)
453 else:
454 batches[batch_data[0]][1] += batch_data[1]
455
456 filterd_batch = []
457 for batch, batch_data in batches.items():
458 if batch_data[1] > 0:
459 filterd_batch.append(tuple(batch_data))
460
461 return filterd_batch
462
463
Rohit Waghchaure114f2b42024-01-14 23:23:55 +0530464def get_batches_from_stock_ledger_entries(searchfields, txt, filters, start=0, page_len=100):
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530465 stock_ledger_entry = frappe.qb.DocType("Stock Ledger Entry")
466 batch_table = frappe.qb.DocType("Batch")
467
468 expiry_date = filters.get("posting_date") or today()
469
470 query = (
471 frappe.qb.from_(stock_ledger_entry)
472 .inner_join(batch_table)
473 .on(batch_table.name == stock_ledger_entry.batch_no)
474 .select(
475 stock_ledger_entry.batch_no,
476 Sum(stock_ledger_entry.actual_qty).as_("qty"),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530477 )
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530478 .where(((batch_table.expiry_date >= expiry_date) | (batch_table.expiry_date.isnull())))
479 .where(stock_ledger_entry.is_cancelled == 0)
480 .where(
481 (stock_ledger_entry.item_code == filters.get("item_code"))
482 & (batch_table.disabled == 0)
483 & (stock_ledger_entry.batch_no.isnotnull())
Ankush Menat494bd9e2022-03-28 18:52:46 +0530484 )
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530485 .groupby(stock_ledger_entry.batch_no, stock_ledger_entry.warehouse)
Rohit Waghchaure114f2b42024-01-14 23:23:55 +0530486 .offset(start)
487 .limit(page_len)
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530488 )
489
490 query = query.select(
491 Concat("MFG-", batch_table.manufacturing_date).as_("manufacturing_date"),
492 Concat("EXP-", batch_table.expiry_date).as_("expiry_date"),
493 )
494
495 if filters.get("warehouse"):
496 query = query.where(stock_ledger_entry.warehouse == filters.get("warehouse"))
497
498 for field in searchfields:
499 query = query.select(batch_table[field])
500
501 if txt:
Rohit Waghchaure114f2b42024-01-14 23:23:55 +0530502 txt_condition = batch_table.name.like("%{0}%".format(txt))
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530503 for field in searchfields + ["name"]:
Rohit Waghchaure114f2b42024-01-14 23:23:55 +0530504 txt_condition |= batch_table[field].like("%{0}%".format(txt))
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530505
506 query = query.where(txt_condition)
507
Rohit Waghchaure114f2b42024-01-14 23:23:55 +0530508 return query.run(as_list=1) or []
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530509
510
Rohit Waghchaure114f2b42024-01-14 23:23:55 +0530511def get_batches_from_serial_and_batch_bundle(searchfields, txt, filters, start=0, page_len=100):
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530512 bundle = frappe.qb.DocType("Serial and Batch Entry")
513 stock_ledger_entry = frappe.qb.DocType("Stock Ledger Entry")
514 batch_table = frappe.qb.DocType("Batch")
515
516 expiry_date = filters.get("posting_date") or today()
517
518 bundle_query = (
519 frappe.qb.from_(bundle)
520 .inner_join(stock_ledger_entry)
521 .on(bundle.parent == stock_ledger_entry.serial_and_batch_bundle)
522 .inner_join(batch_table)
523 .on(batch_table.name == bundle.batch_no)
524 .select(
525 bundle.batch_no,
526 Sum(bundle.qty).as_("qty"),
527 )
528 .where(((batch_table.expiry_date >= expiry_date) | (batch_table.expiry_date.isnull())))
529 .where(stock_ledger_entry.is_cancelled == 0)
530 .where(
531 (stock_ledger_entry.item_code == filters.get("item_code"))
532 & (batch_table.disabled == 0)
533 & (stock_ledger_entry.serial_and_batch_bundle.isnotnull())
534 )
535 .groupby(bundle.batch_no, bundle.warehouse)
Rohit Waghchaure114f2b42024-01-14 23:23:55 +0530536 .offset(start)
537 .limit(page_len)
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530538 )
539
540 bundle_query = bundle_query.select(
541 Concat("MFG-", batch_table.manufacturing_date),
542 Concat("EXP-", batch_table.expiry_date),
543 )
544
545 if filters.get("warehouse"):
546 bundle_query = bundle_query.where(stock_ledger_entry.warehouse == filters.get("warehouse"))
547
548 for field in searchfields:
549 bundle_query = bundle_query.select(batch_table[field])
550
551 if txt:
Rohit Waghchaure114f2b42024-01-14 23:23:55 +0530552 txt_condition = batch_table.name.like("%{0}%".format(txt))
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530553 for field in searchfields + ["name"]:
Rohit Waghchaure114f2b42024-01-14 23:23:55 +0530554 txt_condition |= batch_table[field].like("%{0}%".format(txt))
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530555
556 bundle_query = bundle_query.where(txt_condition)
557
Rohit Waghchaure114f2b42024-01-14 23:23:55 +0530558 return bundle_query.run(as_list=1)
Nabin Haitea4aa042014-05-28 12:56:28 +0530559
Himanshud94a38e2020-05-18 14:26:26 +0530560
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530561@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530562@frappe.validate_and_sanitize_search_inputs
Nabin Haitea4aa042014-05-28 12:56:28 +0530563def get_account_list(doctype, txt, searchfield, start, page_len, filters):
Sagar Vora9baa2222022-08-03 05:42:30 +0000564 doctype = "Account"
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530565 filter_list = []
Nabin Haitea4aa042014-05-28 12:56:28 +0530566
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530567 if isinstance(filters, dict):
568 for key, val in filters.items():
569 if isinstance(val, (list, tuple)):
570 filter_list.append([doctype, key, val[0], val[1]])
571 else:
572 filter_list.append([doctype, key, "=", val])
bhupeshg2e2e973f2015-04-14 22:15:24 +0530573 elif isinstance(filters, list):
574 filter_list.extend(filters)
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530575
Rushabh Mehta38c6b522015-04-23 13:14:17 +0530576 if "is_group" not in [d[1] for d in filter_list]:
577 filter_list.append(["Account", "is_group", "=", "0"])
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530578
579 if searchfield and txt:
580 filter_list.append([doctype, searchfield, "like", "%%%s%%" % txt])
581
Ankush Menat494bd9e2022-03-28 18:52:46 +0530582 return frappe.desk.reportview.execute(
Sagar Vora9baa2222022-08-03 05:42:30 +0000583 doctype,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530584 filters=filter_list,
585 fields=["name", "parent_account"],
586 limit_start=start,
587 limit_page_length=page_len,
588 as_list=True,
589 )
590
Anand Doshifaefeaa2014-06-24 18:53:04 +0530591
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530592@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530593@frappe.validate_and_sanitize_search_inputs
Marica299e2172020-04-28 13:00:04 +0530594def get_blanket_orders(doctype, txt, searchfield, start, page_len, filters):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530595 return frappe.db.sql(
596 """select distinct bo.name, bo.blanket_order_type, bo.to_date
Marica299e2172020-04-28 13:00:04 +0530597 from `tabBlanket Order` bo, `tabBlanket Order Item` boi
598 where
599 boi.parent = bo.name
600 and boi.item_code = {item_code}
601 and bo.blanket_order_type = '{blanket_order_type}'
602 and bo.company = {company}
Ankush Menat494bd9e2022-03-28 18:52:46 +0530603 and bo.docstatus = 1""".format(
604 item_code=frappe.db.escape(filters.get("item")),
605 blanket_order_type=filters.get("blanket_order_type"),
606 company=frappe.db.escape(filters.get("company")),
607 )
608 )
Nabin Haitafd14f62015-10-19 11:55:28 +0530609
Himanshud94a38e2020-05-18 14:26:26 +0530610
Nabin Haitafd14f62015-10-19 11:55:28 +0530611@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530612@frappe.validate_and_sanitize_search_inputs
Nabin Haitafd14f62015-10-19 11:55:28 +0530613def get_income_account(doctype, txt, searchfield, start, page_len, filters):
614 from erpnext.controllers.queries import get_match_cond
615
616 # income account can be any Credit account,
617 # but can also be a Asset account with account_type='Income Account' in special circumstances.
618 # Hence the first condition is an "OR"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530619 if not filters:
620 filters = {}
Nabin Haitafd14f62015-10-19 11:55:28 +0530621
Sagar Vora9baa2222022-08-03 05:42:30 +0000622 doctype = "Account"
Anand Doshi21e09a22015-10-29 12:21:41 +0530623 condition = ""
Nabin Haitafd14f62015-10-19 11:55:28 +0530624 if filters.get("company"):
625 condition += "and tabAccount.company = %(company)s"
Anand Doshi21e09a22015-10-29 12:21:41 +0530626
ruthra kumar6e3e0942023-11-02 17:19:06 +0530627 condition += f"and tabAccount.disabled = {filters.get('disabled', 0)}"
628
Ankush Menat494bd9e2022-03-28 18:52:46 +0530629 return frappe.db.sql(
630 """select tabAccount.name from `tabAccount`
Nabin Haitafd14f62015-10-19 11:55:28 +0530631 where (tabAccount.report_type = "Profit and Loss"
632 or tabAccount.account_type in ("Income Account", "Temporary"))
633 and tabAccount.is_group=0
634 and tabAccount.`{key}` LIKE %(txt)s
Rushabh Mehta3574b372016-03-11 14:33:04 +0530635 {condition} {match_condition}
Ankush Menat494bd9e2022-03-28 18:52:46 +0530636 order by idx desc, name""".format(
637 condition=condition, match_condition=get_match_cond(doctype), key=searchfield
638 ),
639 {"txt": "%" + txt + "%", "company": filters.get("company", "")},
640 )
641
Nabin Hait3a15c922016-03-04 12:30:46 +0530642
Deepesh Garg96e874b2020-11-15 22:43:01 +0530643@frappe.whitelist()
644@frappe.validate_and_sanitize_search_inputs
Ankush Menat6de71eb2023-04-25 18:33:31 +0530645def get_filtered_dimensions(
646 doctype, txt, searchfield, start, page_len, filters, reference_doctype=None
647):
Chillar Anand915b3432021-09-02 16:44:59 +0530648 from erpnext.accounts.doctype.accounting_dimension_filter.accounting_dimension_filter import (
649 get_dimension_filter_map,
650 )
Ankush Menat494bd9e2022-03-28 18:52:46 +0530651
Deepesh Garg96e874b2020-11-15 22:43:01 +0530652 dimension_filters = get_dimension_filter_map()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530653 dimension_filters = dimension_filters.get((filters.get("dimension"), filters.get("account")))
Deepesh Garg6c17b842020-11-25 13:42:16 +0530654 query_filters = []
mergify[bot]071118f2021-11-30 13:15:20 +0000655 or_filters = []
Ankush Menat494bd9e2022-03-28 18:52:46 +0530656 fields = ["name"]
mergify[bot]071118f2021-11-30 13:15:20 +0000657
658 searchfields = frappe.get_meta(doctype).get_search_fields()
Deepesh Garg96e874b2020-11-15 22:43:01 +0530659
660 meta = frappe.get_meta(doctype)
Deepesh Garg96e874b2020-11-15 22:43:01 +0530661 if meta.is_tree:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530662 query_filters.append(["is_group", "=", 0])
Deepesh Garg96e874b2020-11-15 22:43:01 +0530663
Ankush Menat494bd9e2022-03-28 18:52:46 +0530664 if meta.has_field("disabled"):
665 query_filters.append(["disabled", "!=", 1])
Subin Tom333e44e2021-08-18 16:17:54 +0530666
Ankush Menat494bd9e2022-03-28 18:52:46 +0530667 if meta.has_field("company"):
668 query_filters.append(["company", "=", filters.get("company")])
Deepesh Garg6c17b842020-11-25 13:42:16 +0530669
mergify[bot]071118f2021-11-30 13:15:20 +0000670 for field in searchfields:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530671 or_filters.append([field, "LIKE", "%%%s%%" % txt])
mergify[bot]071118f2021-11-30 13:15:20 +0000672 fields.append(field)
Deepesh Garg96e874b2020-11-15 22:43:01 +0530673
674 if dimension_filters:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530675 if dimension_filters["allow_or_restrict"] == "Allow":
676 query_selector = "in"
Deepesh Garg96e874b2020-11-15 22:43:01 +0530677 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530678 query_selector = "not in"
Deepesh Garg96e874b2020-11-15 22:43:01 +0530679
Ankush Menat494bd9e2022-03-28 18:52:46 +0530680 if len(dimension_filters["allowed_dimensions"]) == 1:
681 dimensions = tuple(dimension_filters["allowed_dimensions"] * 2)
Deepesh Garg96e874b2020-11-15 22:43:01 +0530682 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530683 dimensions = tuple(dimension_filters["allowed_dimensions"])
Deepesh Garg96e874b2020-11-15 22:43:01 +0530684
Ankush Menat494bd9e2022-03-28 18:52:46 +0530685 query_filters.append(["name", query_selector, dimensions])
Deepesh Garg96e874b2020-11-15 22:43:01 +0530686
Ankush Menat494bd9e2022-03-28 18:52:46 +0530687 output = frappe.get_list(
Ankush Menat6de71eb2023-04-25 18:33:31 +0530688 doctype,
689 fields=fields,
690 filters=query_filters,
691 or_filters=or_filters,
692 as_list=1,
693 reference_doctype=reference_doctype,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530694 )
Deepesh Garg6c17b842020-11-25 13:42:16 +0530695
mergify[bot]071118f2021-11-30 13:15:20 +0000696 return [tuple(d) for d in set(output)]
Nabin Hait3a15c922016-03-04 12:30:46 +0530697
Ankush Menat494bd9e2022-03-28 18:52:46 +0530698
Nabin Hait3a15c922016-03-04 12:30:46 +0530699@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530700@frappe.validate_and_sanitize_search_inputs
Nabin Hait3a15c922016-03-04 12:30:46 +0530701def get_expense_account(doctype, txt, searchfield, start, page_len, filters):
702 from erpnext.controllers.queries import get_match_cond
Rushabh Mehta203cc962016-04-07 15:25:43 +0530703
Ankush Menat494bd9e2022-03-28 18:52:46 +0530704 if not filters:
705 filters = {}
Nabin Hait3a15c922016-03-04 12:30:46 +0530706
Sagar Vora9baa2222022-08-03 05:42:30 +0000707 doctype = "Account"
Nabin Hait3a15c922016-03-04 12:30:46 +0530708 condition = ""
709 if filters.get("company"):
710 condition += "and tabAccount.company = %(company)s"
Rushabh Mehta203cc962016-04-07 15:25:43 +0530711
Ankush Menat494bd9e2022-03-28 18:52:46 +0530712 return frappe.db.sql(
713 """select tabAccount.name from `tabAccount`
Nabin Hait3a15c922016-03-04 12:30:46 +0530714 where (tabAccount.report_type = "Profit and Loss"
Mangesh-Khairnar5619db22019-08-21 14:49:24 +0530715 or tabAccount.account_type in ("Expense Account", "Fixed Asset", "Temporary", "Asset Received But Not Billed", "Capital Work in Progress"))
Nabin Hait3a15c922016-03-04 12:30:46 +0530716 and tabAccount.is_group=0
717 and tabAccount.docstatus!=2
718 and tabAccount.{key} LIKE %(txt)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530719 {condition} {match_condition}""".format(
720 condition=condition, key=searchfield, match_condition=get_match_cond(doctype)
721 ),
722 {"company": filters.get("company", ""), "txt": "%" + txt + "%"},
723 )
suyashphadtare049a88c2017-01-12 17:49:37 +0530724
725
726@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530727@frappe.validate_and_sanitize_search_inputs
suyashphadtare049a88c2017-01-12 17:49:37 +0530728def warehouse_query(doctype, txt, searchfield, start, page_len, filters):
729 # Should be used when item code is passed in filters.
Sagar Vora9baa2222022-08-03 05:42:30 +0000730 doctype = "Warehouse"
suyashphadtare750a0672017-01-18 15:35:01 +0530731 conditions, bin_conditions = [], []
732 filter_dict = get_doctype_wise_filters(filters)
733
s-aga-ree14faa2024-02-05 21:53:25 +0530734 warehouse_field = "name"
735 meta = frappe.get_meta("Warehouse")
736 if meta.get("show_title_field_in_link") and meta.get("title_field"):
737 searchfield = meta.get("title_field")
738 warehouse_field = meta.get("title_field")
739
740 query = """select `tabWarehouse`.`{warehouse_field}`,
Conor74a782d2022-06-17 06:31:27 -0500741 CONCAT_WS(' : ', 'Actual Qty', ifnull(round(`tabBin`.actual_qty, 2), 0 )) actual_qty
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530742 from `tabWarehouse` left join `tabBin`
743 on `tabBin`.warehouse = `tabWarehouse`.name {bin_conditions}
suyashphadtare34ab1362017-01-31 15:14:44 +0530744 where
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530745 `tabWarehouse`.`{key}` like {txt}
suyashphadtare34ab1362017-01-31 15:14:44 +0530746 {fcond} {mcond}
s-aga-ree14faa2024-02-05 21:53:25 +0530747 order by ifnull(`tabBin`.actual_qty, 0) desc, `tabWarehouse`.`{warehouse_field}` asc
suyashphadtare34ab1362017-01-31 15:14:44 +0530748 limit
Conor00ef4992022-06-14 00:19:07 -0500749 {page_len} offset {start}
suyashphadtare34ab1362017-01-31 15:14:44 +0530750 """.format(
s-aga-ree14faa2024-02-05 21:53:25 +0530751 warehouse_field=warehouse_field,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530752 bin_conditions=get_filters_cond(
753 doctype, filter_dict.get("Bin"), bin_conditions, ignore_permissions=True
754 ),
755 key=searchfield,
756 fcond=get_filters_cond(doctype, filter_dict.get("Warehouse"), conditions),
757 mcond=get_match_cond(doctype),
758 start=start,
759 page_len=page_len,
760 txt=frappe.db.escape("%{0}%".format(txt)),
761 )
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530762
763 return frappe.db.sql(query)
suyashphadtare750a0672017-01-18 15:35:01 +0530764
765
766def get_doctype_wise_filters(filters):
767 # Helper function to seperate filters doctype_wise
768 filter_dict = defaultdict(list)
769 for row in filters:
770 filter_dict[row[0]].append(row)
771 return filter_dict
tundebabzy2a4fefc2017-11-29 06:23:09 +0100772
773
774@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530775@frappe.validate_and_sanitize_search_inputs
tundebabzy2a4fefc2017-11-29 06:23:09 +0100776def get_batch_numbers(doctype, txt, searchfield, start, page_len, filters):
rohitwaghchaure9fbed562018-01-12 16:22:33 +0530777 query = """select batch_id from `tabBatch`
Doridel Cahanap59e4c322018-08-06 17:15:18 +0800778 where disabled = 0
Conorb8f728a2022-06-15 01:37:33 -0500779 and (expiry_date >= CURRENT_DATE or expiry_date IS NULL)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530780 and name like {txt}""".format(
781 txt=frappe.db.escape("%{0}%".format(txt))
782 )
tundebabzy2a4fefc2017-11-29 06:23:09 +0100783
Ankush Menat494bd9e2022-03-28 18:52:46 +0530784 if filters and filters.get("item"):
785 query += " and item = {item}".format(item=frappe.db.escape(filters.get("item")))
tundebabzy2a4fefc2017-11-29 06:23:09 +0100786
Sachin Mane64f48db2018-01-08 17:57:32 +0530787 return frappe.db.sql(query, filters)
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530788
Himanshud94a38e2020-05-18 14:26:26 +0530789
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530790@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530791@frappe.validate_and_sanitize_search_inputs
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530792def item_manufacturer_query(doctype, txt, searchfield, start, page_len, filters):
Maricabac4b932019-09-16 19:44:28 +0530793 item_filters = [
Ankush Menat494bd9e2022-03-28 18:52:46 +0530794 ["manufacturer", "like", "%" + txt + "%"],
795 ["item_code", "=", filters.get("item_code")],
Maricabac4b932019-09-16 19:44:28 +0530796 ]
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530797
Maricabac4b932019-09-16 19:44:28 +0530798 item_manufacturers = frappe.get_all(
799 "Item Manufacturer",
800 fields=["manufacturer", "manufacturer_part_no"],
801 filters=item_filters,
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530802 limit_start=start,
803 limit_page_length=page_len,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530804 as_list=1,
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530805 )
Maricabac4b932019-09-16 19:44:28 +0530806 return item_manufacturers
Saqibd9956092019-11-18 11:46:55 +0530807
Himanshud94a38e2020-05-18 14:26:26 +0530808
Saqibd9956092019-11-18 11:46:55 +0530809@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530810@frappe.validate_and_sanitize_search_inputs
Saqibd9956092019-11-18 11:46:55 +0530811def get_purchase_receipts(doctype, txt, searchfield, start, page_len, filters):
812 query = """
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530813 select pr.name
Saqibd9956092019-11-18 11:46:55 +0530814 from `tabPurchase Receipt` pr, `tabPurchase Receipt Item` pritem
815 where pr.docstatus = 1 and pritem.parent = pr.name
Ankush Menat494bd9e2022-03-28 18:52:46 +0530816 and pr.name like {txt}""".format(
817 txt=frappe.db.escape("%{0}%".format(txt))
818 )
Saqibd9956092019-11-18 11:46:55 +0530819
Ankush Menat494bd9e2022-03-28 18:52:46 +0530820 if filters and filters.get("item_code"):
821 query += " and pritem.item_code = {item_code}".format(
822 item_code=frappe.db.escape(filters.get("item_code"))
823 )
Saqibd9956092019-11-18 11:46:55 +0530824
825 return frappe.db.sql(query, filters)
826
Himanshud94a38e2020-05-18 14:26:26 +0530827
Saqibd9956092019-11-18 11:46:55 +0530828@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530829@frappe.validate_and_sanitize_search_inputs
Saqibd9956092019-11-18 11:46:55 +0530830def get_purchase_invoices(doctype, txt, searchfield, start, page_len, filters):
831 query = """
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530832 select pi.name
Saqibd9956092019-11-18 11:46:55 +0530833 from `tabPurchase Invoice` pi, `tabPurchase Invoice Item` piitem
834 where pi.docstatus = 1 and piitem.parent = pi.name
Ankush Menat494bd9e2022-03-28 18:52:46 +0530835 and pi.name like {txt}""".format(
836 txt=frappe.db.escape("%{0}%".format(txt))
837 )
Saqibd9956092019-11-18 11:46:55 +0530838
Ankush Menat494bd9e2022-03-28 18:52:46 +0530839 if filters and filters.get("item_code"):
840 query += " and piitem.item_code = {item_code}".format(
841 item_code=frappe.db.escape(filters.get("item_code"))
842 )
Saqibd9956092019-11-18 11:46:55 +0530843
844 return frappe.db.sql(query, filters)
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530845
Himanshud94a38e2020-05-18 14:26:26 +0530846
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530847@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530848@frappe.validate_and_sanitize_search_inputs
mergify[bot]b4db5e92023-07-18 17:40:49 +0530849def get_doctypes_for_closing(doctype, txt, searchfield, start, page_len, filters):
850 doctypes = frappe.get_hooks("period_closing_doctypes")
851 if txt:
852 doctypes = [d for d in doctypes if txt.lower() in d.lower()]
853 return [(d,) for d in set(doctypes)]
854
855
856@frappe.whitelist()
857@frappe.validate_and_sanitize_search_inputs
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530858def get_tax_template(doctype, txt, searchfield, start, page_len, filters):
859
Ankush Menat494bd9e2022-03-28 18:52:46 +0530860 item_doc = frappe.get_cached_doc("Item", filters.get("item_code"))
861 item_group = filters.get("item_group")
862 company = filters.get("company")
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530863 taxes = item_doc.taxes or []
864
865 while item_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530866 item_group_doc = frappe.get_cached_doc("Item Group", item_group)
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530867 taxes += item_group_doc.taxes or []
868 item_group = item_group_doc.parent_item_group
869
870 if not taxes:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530871 return frappe.get_all(
872 "Item Tax Template", filters={"disabled": 0, "company": company}, as_list=True
873 )
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530874 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530875 valid_from = filters.get("valid_from")
Marica0fcb05a2020-08-10 14:48:13 +0530876 valid_from = valid_from[1] if isinstance(valid_from, list) else valid_from
877
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530878 args = {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530879 "item_code": filters.get("item_code"),
880 "posting_date": valid_from,
881 "tax_category": filters.get("tax_category"),
882 "company": company,
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530883 }
884
885 taxes = _get_item_tax_template(args, taxes, for_validate=True)
886 return [(d,) for d in set(taxes)]
Himanshud94a38e2020-05-18 14:26:26 +0530887
888
Ankush Menat7eac4a22021-04-19 10:33:39 +0530889def get_fields(doctype, fields=None):
890 if fields is None:
891 fields = []
Himanshud94a38e2020-05-18 14:26:26 +0530892 meta = frappe.get_meta(doctype)
893 fields.extend(meta.get_search_fields())
894
barredterraeb9ee3f2023-12-05 11:22:55 +0100895 if meta.title_field and meta.title_field.strip() not in fields:
Himanshud94a38e2020-05-18 14:26:26 +0530896 fields.insert(1, meta.title_field.strip())
897
898 return unique(fields)
ruthra kumar662ccd42023-07-22 11:18:11 +0530899
900
901@frappe.whitelist()
902@frappe.validate_and_sanitize_search_inputs
903def get_payment_terms_for_references(doctype, txt, searchfield, start, page_len, filters) -> list:
904 terms = []
905 if filters:
906 terms = frappe.db.get_all(
907 "Payment Schedule",
908 filters={"parent": filters.get("reference")},
909 fields=["payment_term"],
910 limit=page_len,
911 as_list=1,
912 )
913 return terms
s-aga-r00261092023-12-04 18:00:06 +0530914
915
916@frappe.whitelist()
917@frappe.validate_and_sanitize_search_inputs
918def get_filtered_child_rows(doctype, txt, searchfield, start, page_len, filters) -> list:
919 table = frappe.qb.DocType(doctype)
920 query = (
921 frappe.qb.from_(table)
922 .select(
923 table.name,
924 Concat("#", table.idx, ", ", table.item_code),
925 )
926 .orderby(table.idx)
927 .offset(start)
928 .limit(page_len)
929 )
930
931 if filters:
932 for field, value in filters.items():
933 query = query.where(table[field] == value)
934
935 if txt:
936 txt += "%"
937 query = query.where(
938 ((table.idx.like(txt.replace("#", ""))) | (table.item_code.like(txt))) | (table.name.like(txt))
939 )
940
941 return query.run(as_dict=False)