blob: 8eae0a0702813049931710931b80216b2e44de05 [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
suyashphadtare750a0672017-01-18 15:35:01 +05306from collections import defaultdict
Chillar Anand915b3432021-09-02 16:44:59 +05307
8import frappe
DeeMysterioaa826242021-09-14 13:58:18 +05309from frappe import scrub
Chillar Anand915b3432021-09-02 16:44:59 +053010from frappe.desk.reportview import get_filters_cond, get_match_cond
11from frappe.utils import nowdate, unique
12
13import erpnext
Deepesh Gargef0d26c2020-01-06 15:34:15 +053014from erpnext.stock.get_item_details import _get_item_tax_template
Chillar Anand915b3432021-09-02 16:44:59 +053015
Saurabh02875592013-07-08 18:45:55 +053016
Chinmay D. Paiaa121092020-07-01 21:14:32 +053017# searches for active employees
18@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +053019@frappe.validate_and_sanitize_search_inputs
Saurabh02875592013-07-08 18:45:55 +053020def employee_query(doctype, txt, searchfield, start, page_len, filters):
Sagar Vora9baa2222022-08-03 05:42:30 +000021 doctype = "Employee"
Kanchan Chauhan7652b852016-11-16 15:29:01 +053022 conditions = []
Sagar Vora9baa2222022-08-03 05:42:30 +000023 fields = get_fields(doctype, ["name", "employee_name"])
Himanshud94a38e2020-05-18 14:26:26 +053024
Ankush Menat494bd9e2022-03-28 18:52:46 +053025 return frappe.db.sql(
26 """select {fields} from `tabEmployee`
Anurag Mishrafc98abe2021-06-23 11:21:38 +053027 where status in ('Active', 'Suspended')
Anand Doshibd67e872014-04-11 16:51:27 +053028 and docstatus < 2
Anand Doshi48d3b542014-07-09 13:15:03 +053029 and ({key} like %(txt)s
30 or employee_name like %(txt)s)
Kanchan Chauhan7652b852016-11-16 15:29:01 +053031 {fcond} {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +053032 order by
Conorea28ed12022-06-17 10:47:48 -050033 (case when locate(%(_txt)s, name) > 0 then locate(%(_txt)s, name) else 99999 end),
34 (case when locate(%(_txt)s, employee_name) > 0 then locate(%(_txt)s, employee_name) else 99999 end),
Rushabh Mehta3574b372016-03-11 14:33:04 +053035 idx desc,
Anand Doshi652bc072014-04-16 15:21:46 +053036 name, employee_name
Conor00ef4992022-06-14 00:19:07 -050037 limit %(page_len)s offset %(start)s""".format(
Ankush Menat494bd9e2022-03-28 18:52:46 +053038 **{
39 "fields": ", ".join(fields),
40 "key": searchfield,
41 "fcond": get_filters_cond(doctype, filters, conditions),
42 "mcond": get_match_cond(doctype),
43 }
44 ),
45 {"txt": "%%%s%%" % txt, "_txt": txt.replace("%", ""), "start": start, "page_len": page_len},
46 )
Saurabh02875592013-07-08 18:45:55 +053047
Himanshud94a38e2020-05-18 14:26:26 +053048
49# searches for leads which are not converted
Chinmay D. Paiaa121092020-07-01 21:14:32 +053050@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +053051@frappe.validate_and_sanitize_search_inputs
Anand Doshibd67e872014-04-11 16:51:27 +053052def lead_query(doctype, txt, searchfield, start, page_len, filters):
Sagar Vora9baa2222022-08-03 05:42:30 +000053 doctype = "Lead"
54 fields = get_fields(doctype, ["name", "lead_name", "company_name"])
Himanshud94a38e2020-05-18 14:26:26 +053055
Ankush Menat494bd9e2022-03-28 18:52:46 +053056 return frappe.db.sql(
57 """select {fields} from `tabLead`
Anand Doshibd67e872014-04-11 16:51:27 +053058 where docstatus < 2
59 and ifnull(status, '') != 'Converted'
Anand Doshi48d3b542014-07-09 13:15:03 +053060 and ({key} like %(txt)s
61 or lead_name like %(txt)s
62 or company_name like %(txt)s)
63 {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +053064 order by
Conorea28ed12022-06-17 10:47:48 -050065 (case when locate(%(_txt)s, name) > 0 then locate(%(_txt)s, name) else 99999 end),
66 (case when locate(%(_txt)s, lead_name) > 0 then locate(%(_txt)s, lead_name) else 99999 end),
67 (case when locate(%(_txt)s, company_name) > 0 then locate(%(_txt)s, company_name) else 99999 end),
Rushabh Mehta3574b372016-03-11 14:33:04 +053068 idx desc,
Anand Doshi652bc072014-04-16 15:21:46 +053069 name, lead_name
Conor00ef4992022-06-14 00:19:07 -050070 limit %(page_len)s offset %(start)s""".format(
Ankush Menat494bd9e2022-03-28 18:52:46 +053071 **{"fields": ", ".join(fields), "key": searchfield, "mcond": get_match_cond(doctype)}
72 ),
73 {"txt": "%%%s%%" % txt, "_txt": txt.replace("%", ""), "start": start, "page_len": page_len},
74 )
75
76 # searches for customer
Saurabh02875592013-07-08 18:45:55 +053077
Himanshud94a38e2020-05-18 14:26:26 +053078
Chinmay D. Paiaa121092020-07-01 21:14:32 +053079@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +053080@frappe.validate_and_sanitize_search_inputs
Saurabh02875592013-07-08 18:45:55 +053081def customer_query(doctype, txt, searchfield, start, page_len, filters):
Sagar Vora9baa2222022-08-03 05:42:30 +000082 doctype = "Customer"
KanchanChauhan4b888b92017-07-25 14:03:01 +053083 conditions = []
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053084 cust_master_name = frappe.defaults.get_user_default("cust_master_name")
Saurabhf52dc072013-07-10 13:07:49 +053085
Saurabh02875592013-07-08 18:45:55 +053086 if cust_master_name == "Customer Name":
87 fields = ["name", "customer_group", "territory"]
88 else:
89 fields = ["name", "customer_name", "customer_group", "territory"]
Rushabh Mehtab92087c2017-01-13 18:53:11 +053090
Sagar Vora9baa2222022-08-03 05:42:30 +000091 fields = get_fields(doctype, fields)
Saurabhf52dc072013-07-10 13:07:49 +053092
Sagar Vora9baa2222022-08-03 05:42:30 +000093 searchfields = frappe.get_meta(doctype).get_search_fields()
Ankush Menata9c84f72021-06-11 16:00:48 +053094 searchfields = " or ".join(field + " like %(txt)s" for field in searchfields)
Saurabh02875592013-07-08 18:45:55 +053095
Ankush Menat494bd9e2022-03-28 18:52:46 +053096 return frappe.db.sql(
97 """select {fields} from `tabCustomer`
Anand Doshibd67e872014-04-11 16:51:27 +053098 where docstatus < 2
Console Admin86231662017-06-23 20:32:52 +030099 and ({scond}) and disabled=0
KanchanChauhan4b888b92017-07-25 14:03:01 +0530100 {fcond} {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +0530101 order by
Conorea28ed12022-06-17 10:47:48 -0500102 (case when locate(%(_txt)s, name) > 0 then locate(%(_txt)s, name) else 99999 end),
103 (case when locate(%(_txt)s, customer_name) > 0 then locate(%(_txt)s, customer_name) else 99999 end),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530104 idx desc,
Anand Doshibd67e872014-04-11 16:51:27 +0530105 name, customer_name
Conor00ef4992022-06-14 00:19:07 -0500106 limit %(page_len)s offset %(start)s""".format(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530107 **{
108 "fields": ", ".join(fields),
109 "scond": searchfields,
110 "mcond": get_match_cond(doctype),
111 "fcond": get_filters_cond(doctype, filters, conditions).replace("%", "%%"),
112 }
113 ),
114 {"txt": "%%%s%%" % txt, "_txt": txt.replace("%", ""), "start": start, "page_len": page_len},
115 )
Saurabh02875592013-07-08 18:45:55 +0530116
Himanshud94a38e2020-05-18 14:26:26 +0530117
Saurabh02875592013-07-08 18:45:55 +0530118# searches for supplier
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530119@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530120@frappe.validate_and_sanitize_search_inputs
Saurabh02875592013-07-08 18:45:55 +0530121def supplier_query(doctype, txt, searchfield, start, page_len, filters):
Sagar Vora9baa2222022-08-03 05:42:30 +0000122 doctype = "Supplier"
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530123 supp_master_name = frappe.defaults.get_user_default("supp_master_name")
Suraj Shetty1923ef02020-08-05 19:42:25 +0530124
Anand Doshibd67e872014-04-11 16:51:27 +0530125 if supp_master_name == "Supplier Name":
Zlash652e080982018-04-19 18:37:53 +0530126 fields = ["name", "supplier_group"]
Anand Doshibd67e872014-04-11 16:51:27 +0530127 else:
Zlash652e080982018-04-19 18:37:53 +0530128 fields = ["name", "supplier_name", "supplier_group"]
Himanshud94a38e2020-05-18 14:26:26 +0530129
Sagar Vora9baa2222022-08-03 05:42:30 +0000130 fields = get_fields(doctype, fields)
Saurabh02875592013-07-08 18:45:55 +0530131
Ankush Menat494bd9e2022-03-28 18:52:46 +0530132 return frappe.db.sql(
133 """select {field} from `tabSupplier`
Anand Doshibd67e872014-04-11 16:51:27 +0530134 where docstatus < 2
Anand Doshi48d3b542014-07-09 13:15:03 +0530135 and ({key} like %(txt)s
Ankush Menat2221c9e2021-10-27 19:15:44 +0530136 or supplier_name like %(txt)s) and disabled=0
Conorea28ed12022-06-17 10:47:48 -0500137 and (on_hold = 0 or (on_hold = 1 and CURRENT_DATE > release_date))
Anand Doshi48d3b542014-07-09 13:15:03 +0530138 {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +0530139 order by
Conorea28ed12022-06-17 10:47:48 -0500140 (case when locate(%(_txt)s, name) > 0 then locate(%(_txt)s, name) else 99999 end),
141 (case when locate(%(_txt)s, supplier_name) > 0 then locate(%(_txt)s, supplier_name) else 99999 end),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530142 idx desc,
Anand Doshibd67e872014-04-11 16:51:27 +0530143 name, supplier_name
Conor00ef4992022-06-14 00:19:07 -0500144 limit %(page_len)s offset %(start)s""".format(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530145 **{"field": ", ".join(fields), "key": searchfield, "mcond": get_match_cond(doctype)}
146 ),
147 {"txt": "%%%s%%" % txt, "_txt": txt.replace("%", ""), "start": start, "page_len": page_len},
148 )
Anand Doshibd67e872014-04-11 16:51:27 +0530149
Himanshud94a38e2020-05-18 14:26:26 +0530150
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530151@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530152@frappe.validate_and_sanitize_search_inputs
Nabin Hait9a380ef2013-07-16 17:24:17 +0530153def tax_account_query(doctype, txt, searchfield, start, page_len, filters):
Sagar Vora9baa2222022-08-03 05:42:30 +0000154 doctype = "Account"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530155 company_currency = erpnext.get_company_currency(filters.get("company"))
Deepesh Gargfbf6e562020-03-31 10:45:32 +0530156
Suraj Shetty1923ef02020-08-05 19:42:25 +0530157 def get_accounts(with_account_type_filter):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530158 account_type_condition = ""
Suraj Shetty1923ef02020-08-05 19:42:25 +0530159 if with_account_type_filter:
160 account_type_condition = "AND account_type in %(account_types)s"
161
Ankush Menat494bd9e2022-03-28 18:52:46 +0530162 accounts = frappe.db.sql(
163 """
Suraj Shetty1923ef02020-08-05 19:42:25 +0530164 SELECT name, parent_account
165 FROM `tabAccount`
166 WHERE `tabAccount`.docstatus!=2
167 {account_type_condition}
168 AND is_group = 0
169 AND company = %(company)s
Saqib Ansaria1e3ae82022-05-11 13:01:06 +0530170 AND disabled = %(disabled)s
Deepesh Garg57924592022-03-22 18:26:58 +0530171 AND (account_currency = %(currency)s or ifnull(account_currency, '') = '')
Suraj Shetty1923ef02020-08-05 19:42:25 +0530172 AND `{searchfield}` LIKE %(txt)s
prssannade7a2bc2020-09-21 13:57:04 +0530173 {mcond}
Suraj Shetty1923ef02020-08-05 19:42:25 +0530174 ORDER BY idx DESC, name
Conor00ef4992022-06-14 00:19:07 -0500175 LIMIT %(limit)s offset %(offset)s
prssannade7a2bc2020-09-21 13:57:04 +0530176 """.format(
177 account_type_condition=account_type_condition,
178 searchfield=searchfield,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530179 mcond=get_match_cond(doctype),
prssannade7a2bc2020-09-21 13:57:04 +0530180 ),
Suraj Shetty1923ef02020-08-05 19:42:25 +0530181 dict(
182 account_types=filters.get("account_type"),
183 company=filters.get("company"),
Saqib Ansaria1e3ae82022-05-11 13:01:06 +0530184 disabled=filters.get("disabled", 0),
Suraj Shetty1923ef02020-08-05 19:42:25 +0530185 currency=company_currency,
186 txt="%{}%".format(txt),
187 offset=start,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530188 limit=page_len,
189 ),
Suraj Shetty1923ef02020-08-05 19:42:25 +0530190 )
191
192 return accounts
193
194 tax_accounts = get_accounts(True)
195
Nabin Hait0c21e2a2014-03-21 11:14:49 +0530196 if not tax_accounts:
Suraj Shetty1923ef02020-08-05 19:42:25 +0530197 tax_accounts = get_accounts(False)
Anand Doshibd67e872014-04-11 16:51:27 +0530198
Nabin Hait0c21e2a2014-03-21 11:14:49 +0530199 return tax_accounts
Saurabh02875592013-07-08 18:45:55 +0530200
Himanshud94a38e2020-05-18 14:26:26 +0530201
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530202@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530203@frappe.validate_and_sanitize_search_inputs
Rushabh Mehta203cc962016-04-07 15:25:43 +0530204def item_query(doctype, txt, searchfield, start, page_len, filters, as_dict=False):
Sagar Vora9baa2222022-08-03 05:42:30 +0000205 doctype = "Item"
Saurabh02875592013-07-08 18:45:55 +0530206 conditions = []
Saurabhf52dc072013-07-10 13:07:49 +0530207
rohitwaghchaurec59371a2021-06-03 20:02:58 +0530208 if isinstance(filters, str):
209 filters = json.loads(filters)
210
Ankush Menat494bd9e2022-03-28 18:52:46 +0530211 # Get searchfields from meta and use in Item Link field query
Sagar Vora9baa2222022-08-03 05:42:30 +0000212 meta = frappe.get_meta(doctype, cached=True)
marination3dbef9d2019-10-28 15:48:10 +0530213 searchfields = meta.get_search_fields()
214
Ankush Menat494bd9e2022-03-28 18:52:46 +0530215 columns = ""
Rohit Waghchaurefd889fd2022-09-28 23:00:45 +0530216 extra_searchfields = [field for field in searchfields if not field in ["name", "description"]]
Rohit Waghchaurec42312e2019-11-19 19:05:23 +0530217
218 if extra_searchfields:
Rohit Waghchaurefd889fd2022-09-28 23:00:45 +0530219 columns += ", " + ", ".join(extra_searchfields)
220
221 if "description" in searchfields:
222 columns += """, if(length(tabItem.description) > 40, \
223 concat(substr(tabItem.description, 1, 40), "..."), description) as description"""
marination1e754b12019-10-30 18:33:44 +0530224
Ankush Menat494bd9e2022-03-28 18:52:46 +0530225 searchfields = searchfields + [
226 field
227 for field in [searchfield or "name", "item_code", "item_group", "item_name"]
228 if not field in searchfields
229 ]
marination3dbef9d2019-10-28 15:48:10 +0530230 searchfields = " or ".join([field + " like %(txt)s" for field in searchfields])
231
DeeMysterioaa826242021-09-14 13:58:18 +0530232 if filters and isinstance(filters, dict):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530233 if filters.get("customer") or filters.get("supplier"):
234 party = filters.get("customer") or filters.get("supplier")
235 item_rules_list = frappe.get_all(
236 "Party Specific Item", filters={"party": party}, fields=["restrict_based_on", "based_on_value"]
237 )
Rohit Waghchaure721b4132021-06-02 14:13:09 +0530238
DeeMysterioaa826242021-09-14 13:58:18 +0530239 filters_dict = {}
240 for rule in item_rules_list:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530241 if rule["restrict_based_on"] == "Item":
242 rule["restrict_based_on"] = "name"
DeeMysterioaa826242021-09-14 13:58:18 +0530243 filters_dict[rule.restrict_based_on] = []
noahjacobca2fb472021-05-12 16:25:07 +0530244
DeeMysterioaa826242021-09-14 13:58:18 +0530245 for rule in item_rules_list:
246 filters_dict[rule.restrict_based_on].append(rule.based_on_value)
noahjacobca2fb472021-05-12 16:25:07 +0530247
DeeMysterioaa826242021-09-14 13:58:18 +0530248 for filter in filters_dict:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530249 filters[scrub(filter)] = ["in", filters_dict[filter]]
DeeMysterioaa826242021-09-14 13:58:18 +0530250
Ankush Menat494bd9e2022-03-28 18:52:46 +0530251 if filters.get("customer"):
252 del filters["customer"]
DeeMysterioaa826242021-09-14 13:58:18 +0530253 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530254 del filters["supplier"]
Ankush Menat41a95e52022-02-03 13:02:13 +0530255 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530256 filters.pop("customer", None)
257 filters.pop("supplier", None)
DeeMysterioaa826242021-09-14 13:58:18 +0530258
Ankush Menat494bd9e2022-03-28 18:52:46 +0530259 description_cond = ""
Sagar Vora9baa2222022-08-03 05:42:30 +0000260 if frappe.db.count(doctype, cache=True) < 50000:
Rushabh Mehtad5f9ebd2018-04-02 23:37:33 +0530261 # scan description only if items are less than 50000
Ankush Menat494bd9e2022-03-28 18:52:46 +0530262 description_cond = "or tabItem.description LIKE %(txt)s"
Rohit Waghchaurefd889fd2022-09-28 23:00:45 +0530263
Ankush Menat494bd9e2022-03-28 18:52:46 +0530264 return frappe.db.sql(
265 """select
Rohit Waghchaurefd889fd2022-09-28 23:00:45 +0530266 tabItem.name {columns}
Anand Doshibd67e872014-04-11 16:51:27 +0530267 from tabItem
Anand Doshi22c0d782013-11-04 16:23:04 +0530268 where tabItem.docstatus < 2
Anand Doshi21e09a22015-10-29 12:21:41 +0530269 and tabItem.disabled=0
rohitwaghchaure79789072020-05-21 18:10:13 +0530270 and tabItem.has_variants=0
Rushabh Mehta864d1ea2014-06-23 12:20:12 +0530271 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 +0530272 and ({scond} or tabItem.item_code IN (select parent from `tabItem Barcode` where barcode LIKE %(txt)s)
Rohit Waghchaure2bfb0632019-03-02 21:47:55 +0530273 {description_cond})
Anand Doshi22c0d782013-11-04 16:23:04 +0530274 {fcond} {mcond}
Anand Doshi652bc072014-04-16 15:21:46 +0530275 order by
276 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
277 if(locate(%(_txt)s, item_name), locate(%(_txt)s, item_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530278 idx desc,
Anand Doshi652bc072014-04-16 15:21:46 +0530279 name, item_name
Rushabh Mehtabc4e2cd2017-10-17 12:30:34 +0530280 limit %(start)s, %(page_len)s """.format(
marination1e754b12019-10-30 18:33:44 +0530281 columns=columns,
marination3dbef9d2019-10-28 15:48:10 +0530282 scond=searchfields,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530283 fcond=get_filters_cond(doctype, filters, conditions).replace("%", "%%"),
284 mcond=get_match_cond(doctype).replace("%", "%%"),
285 description_cond=description_cond,
286 ),
287 {
288 "today": nowdate(),
289 "txt": "%%%s%%" % txt,
290 "_txt": txt.replace("%", ""),
291 "start": start,
292 "page_len": page_len,
293 },
294 as_dict=as_dict,
295 )
Saurabh02875592013-07-08 18:45:55 +0530296
Himanshud94a38e2020-05-18 14:26:26 +0530297
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530298@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530299@frappe.validate_and_sanitize_search_inputs
Saurabh022ab632017-11-10 15:06:02 +0530300def bom(doctype, txt, searchfield, start, page_len, filters):
Sagar Vora9baa2222022-08-03 05:42:30 +0000301 doctype = "BOM"
Anand Doshibd67e872014-04-11 16:51:27 +0530302 conditions = []
Sagar Vora9baa2222022-08-03 05:42:30 +0000303 fields = get_fields(doctype, ["name", "item"])
Saurabhf52dc072013-07-10 13:07:49 +0530304
Ankush Menat494bd9e2022-03-28 18:52:46 +0530305 return frappe.db.sql(
306 """select {fields}
Conorea28ed12022-06-17 10:47:48 -0500307 from `tabBOM`
308 where `tabBOM`.docstatus=1
309 and `tabBOM`.is_active=1
310 and `tabBOM`.`{key}` like %(txt)s
Nabin Hait62211172016-03-16 16:22:03 +0530311 {fcond} {mcond}
312 order by
Conorea28ed12022-06-17 10:47:48 -0500313 (case when locate(%(_txt)s, name) > 0 then locate(%(_txt)s, name) else 99999 end),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530314 idx desc, name
Conorea28ed12022-06-17 10:47:48 -0500315 limit %(page_len)s offset %(start)s""".format(
Himanshud94a38e2020-05-18 14:26:26 +0530316 fields=", ".join(fields),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530317 fcond=get_filters_cond(doctype, filters, conditions).replace("%", "%%"),
318 mcond=get_match_cond(doctype).replace("%", "%%"),
319 key=searchfield,
320 ),
Mangesh-Khairnar6a796912019-07-08 10:40:40 +0530321 {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530322 "txt": "%" + txt + "%",
323 "_txt": txt.replace("%", ""),
324 "start": start or 0,
325 "page_len": page_len or 20,
326 },
327 )
Saurabh02875592013-07-08 18:45:55 +0530328
Himanshud94a38e2020-05-18 14:26:26 +0530329
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530330@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530331@frappe.validate_and_sanitize_search_inputs
Saurabh02875592013-07-08 18:45:55 +0530332def get_project_name(doctype, txt, searchfield, start, page_len, filters):
Sagar Vora9baa2222022-08-03 05:42:30 +0000333 doctype = "Project"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530334 cond = ""
335 if filters and filters.get("customer"):
Suraj Shetty6ea3de92018-09-26 18:15:53 +0530336 cond = """(`tabProject`.customer = %s or
Ankush Menat494bd9e2022-03-28 18:52:46 +0530337 ifnull(`tabProject`.customer,"")="") and""" % (
338 frappe.db.escape(filters.get("customer"))
339 )
Anand Doshibd67e872014-04-11 16:51:27 +0530340
Sagar Vora9baa2222022-08-03 05:42:30 +0000341 fields = get_fields(doctype, ["name", "project_name"])
342 searchfields = frappe.get_meta(doctype).get_search_fields()
Conor74a782d2022-06-17 06:31:27 -0500343 searchfields = " or ".join(["`tabProject`." + field + " like %(txt)s" for field in searchfields])
Himanshud94a38e2020-05-18 14:26:26 +0530344
Ankush Menat494bd9e2022-03-28 18:52:46 +0530345 return frappe.db.sql(
346 """select {fields} from `tabProject`
Rucha Mahabal062d3012021-05-07 13:31:14 +0530347 where
Conor74a782d2022-06-17 06:31:27 -0500348 `tabProject`.status not in ('Completed', 'Cancelled')
Subin Tom889140f2021-06-22 16:26:19 +0530349 and {cond} {scond} {match_cond}
Rushabh Mehta3574b372016-03-11 14:33:04 +0530350 order by
Conorea28ed12022-06-17 10:47:48 -0500351 (case when locate(%(_txt)s, `tabProject`.name) > 0 then locate(%(_txt)s, `tabProject`.name) else 99999 end),
352 `tabProject`.idx desc,
Rushabh Mehta3574b372016-03-11 14:33:04 +0530353 `tabProject`.name asc
Conor00ef4992022-06-14 00:19:07 -0500354 limit {page_len} offset {start}""".format(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530355 fields=", ".join(["`tabProject`.{0}".format(f) for f in fields]),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530356 cond=cond,
Rucha Mahabal062d3012021-05-07 13:31:14 +0530357 scond=searchfields,
Rushabh Mehta3574b372016-03-11 14:33:04 +0530358 match_cond=get_match_cond(doctype),
359 start=start,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530360 page_len=page_len,
361 ),
362 {"txt": "%{0}%".format(txt), "_txt": txt.replace("%", "")},
363 )
Anand Doshibd67e872014-04-11 16:51:27 +0530364
tundebabzyf6d738b2017-09-18 12:40:09 +0100365
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530366@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530367@frappe.validate_and_sanitize_search_inputs
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530368def get_delivery_notes_to_be_billed(doctype, txt, searchfield, start, page_len, filters, as_dict):
Sagar Vora9baa2222022-08-03 05:42:30 +0000369 doctype = "Delivery Note"
370 fields = get_fields(doctype, ["name", "customer", "posting_date"])
Himanshud94a38e2020-05-18 14:26:26 +0530371
Ankush Menat494bd9e2022-03-28 18:52:46 +0530372 return frappe.db.sql(
373 """
Himanshud94a38e2020-05-18 14:26:26 +0530374 select %(fields)s
Anand Doshibd67e872014-04-11 16:51:27 +0530375 from `tabDelivery Note`
376 where `tabDelivery Note`.`%(key)s` like %(txt)s and
tundebabzyf6d738b2017-09-18 12:40:09 +0100377 `tabDelivery Note`.docstatus = 1
Conor74a782d2022-06-17 06:31:27 -0500378 and status not in ('Stopped', 'Closed') %(fcond)s
tundebabzyf6d738b2017-09-18 12:40:09 +0100379 and (
380 (`tabDelivery Note`.is_return = 0 and `tabDelivery Note`.per_billed < 100)
Deepesh Garge2dc1022021-04-14 11:21:11 +0530381 or (`tabDelivery Note`.grand_total = 0 and `tabDelivery Note`.per_billed < 100)
tundebabzyf6d738b2017-09-18 12:40:09 +0100382 or (
383 `tabDelivery Note`.is_return = 1
384 and return_against in (select name from `tabDelivery Note` where per_billed < 100)
385 )
386 )
Conor00ef4992022-06-14 00:19:07 -0500387 %(mcond)s order by `tabDelivery Note`.`%(key)s` asc limit %(page_len)s offset %(start)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530388 """
389 % {
390 "fields": ", ".join(["`tabDelivery Note`.{0}".format(f) for f in fields]),
391 "key": searchfield,
392 "fcond": get_filters_cond(doctype, filters, []),
393 "mcond": get_match_cond(doctype),
394 "start": start,
395 "page_len": page_len,
396 "txt": "%(txt)s",
397 },
398 {"txt": ("%%%s%%" % txt)},
399 as_dict=as_dict,
400 )
tundebabzyf6d738b2017-09-18 12:40:09 +0100401
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530402
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530403@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530404@frappe.validate_and_sanitize_search_inputs
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530405def get_batch_no(doctype, txt, searchfield, start, page_len, filters):
Sagar Vora9baa2222022-08-03 05:42:30 +0000406 doctype = "Batch"
Neil Trini Lasradoebb60f52015-07-08 14:36:09 +0530407 cond = ""
408 if filters.get("posting_date"):
Nabin Hait7918b922018-01-31 15:30:03 +0530409 cond = "and (batch.expiry_date is null or batch.expiry_date >= %(posting_date)s)"
Rushabh Mehtab6398be2015-08-26 10:50:16 +0530410
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530411 batch_nos = None
412 args = {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530413 "item_code": filters.get("item_code"),
414 "warehouse": filters.get("warehouse"),
415 "posting_date": filters.get("posting_date"),
416 "txt": "%{0}%".format(txt),
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530417 "start": start,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530418 "page_len": page_len,
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530419 }
420
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530421 having_clause = "having sum(sle.actual_qty) > 0"
422 if filters.get("is_return"):
423 having_clause = ""
424
Sagar Vora9baa2222022-08-03 05:42:30 +0000425 meta = frappe.get_meta(doctype, cached=True)
Deepesh Garga0d192e2020-09-22 13:54:07 +0530426 searchfields = meta.get_search_fields()
427
Ankush Menat494bd9e2022-03-28 18:52:46 +0530428 search_columns = ""
429 search_cond = ""
Deepesh Gargf58a5ec2020-10-05 13:55:53 +0530430
Deepesh Garga0d192e2020-09-22 13:54:07 +0530431 if searchfields:
432 search_columns = ", " + ", ".join(searchfields)
Deepesh Garg1fae7742020-10-05 12:38:54 +0530433 search_cond = " or " + " or ".join([field + " like %(txt)s" for field in searchfields])
Deepesh Garga0d192e2020-09-22 13:54:07 +0530434
Ankush Menat494bd9e2022-03-28 18:52:46 +0530435 if args.get("warehouse"):
436 searchfields = ["batch." + field for field in searchfields]
Deepesh Garga0d192e2020-09-22 13:54:07 +0530437 if searchfields:
438 search_columns = ", " + ", ".join(searchfields)
Deepesh Garg1fae7742020-10-05 12:38:54 +0530439 search_cond = " or " + " or ".join([field + " like %(txt)s" for field in searchfields])
Deepesh Garga0d192e2020-09-22 13:54:07 +0530440
Ankush Menat494bd9e2022-03-28 18:52:46 +0530441 batch_nos = frappe.db.sql(
442 """select sle.batch_no, round(sum(sle.actual_qty),2), sle.stock_uom,
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530443 concat('MFG-',batch.manufacturing_date), concat('EXP-',batch.expiry_date)
Deepesh Garga0d192e2020-09-22 13:54:07 +0530444 {search_columns}
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530445 from `tabStock Ledger Entry` sle
446 INNER JOIN `tabBatch` batch on sle.batch_no = batch.name
447 where
448 batch.disabled = 0
Rohit Waghchaurec14aa452021-07-20 18:19:15 +0530449 and sle.is_cancelled = 0
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530450 and sle.item_code = %(item_code)s
451 and sle.warehouse = %(warehouse)s
452 and (sle.batch_no like %(txt)s
Sun Howwrongbum088be372019-12-24 12:29:25 +0530453 or batch.expiry_date like %(txt)s
Deepesh Gargf58a5ec2020-10-05 13:55:53 +0530454 or batch.manufacturing_date like %(txt)s
455 {search_cond})
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530456 and batch.docstatus < 2
457 {cond}
458 {match_conditions}
459 group by batch_no {having_clause}
460 order by batch.expiry_date, sle.batch_no desc
Conor00ef4992022-06-14 00:19:07 -0500461 limit %(page_len)s offset %(start)s""".format(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530462 search_columns=search_columns,
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530463 cond=cond,
464 match_conditions=get_match_cond(doctype),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530465 having_clause=having_clause,
466 search_cond=search_cond,
467 ),
468 args,
469 )
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530470
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530471 return batch_nos
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530472 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530473 return frappe.db.sql(
474 """select name, concat('MFG-', manufacturing_date), concat('EXP-',expiry_date)
Deepesh Garga0d192e2020-09-22 13:54:07 +0530475 {search_columns}
476 from `tabBatch` batch
Doridel Cahanap59e4c322018-08-06 17:15:18 +0800477 where batch.disabled = 0
478 and item = %(item_code)s
sivankar621740e2018-02-12 14:33:40 +0530479 and (name like %(txt)s
Sun Howwrongbum088be372019-12-24 12:29:25 +0530480 or expiry_date like %(txt)s
Deepesh Gargf58a5ec2020-10-05 13:55:53 +0530481 or manufacturing_date like %(txt)s
482 {search_cond})
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530483 and docstatus < 2
Neil Trini Lasradoebb60f52015-07-08 14:36:09 +0530484 {0}
Anand Doshi0dc79f42015-04-06 12:59:34 +0530485 {match_conditions}
Deepesh Gargf58a5ec2020-10-05 13:55:53 +0530486
Anand Doshi0dc79f42015-04-06 12:59:34 +0530487 order by expiry_date, name desc
Conor00ef4992022-06-14 00:19:07 -0500488 limit %(page_len)s offset %(start)s""".format(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530489 cond,
490 search_columns=search_columns,
491 search_cond=search_cond,
492 match_conditions=get_match_cond(doctype),
493 ),
494 args,
495 )
Nabin Haitea4aa042014-05-28 12:56:28 +0530496
Himanshud94a38e2020-05-18 14:26:26 +0530497
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530498@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530499@frappe.validate_and_sanitize_search_inputs
Nabin Haitea4aa042014-05-28 12:56:28 +0530500def get_account_list(doctype, txt, searchfield, start, page_len, filters):
Sagar Vora9baa2222022-08-03 05:42:30 +0000501 doctype = "Account"
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530502 filter_list = []
Nabin Haitea4aa042014-05-28 12:56:28 +0530503
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530504 if isinstance(filters, dict):
505 for key, val in filters.items():
506 if isinstance(val, (list, tuple)):
507 filter_list.append([doctype, key, val[0], val[1]])
508 else:
509 filter_list.append([doctype, key, "=", val])
bhupeshg2e2e973f2015-04-14 22:15:24 +0530510 elif isinstance(filters, list):
511 filter_list.extend(filters)
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530512
Rushabh Mehta38c6b522015-04-23 13:14:17 +0530513 if "is_group" not in [d[1] for d in filter_list]:
514 filter_list.append(["Account", "is_group", "=", "0"])
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530515
516 if searchfield and txt:
517 filter_list.append([doctype, searchfield, "like", "%%%s%%" % txt])
518
Ankush Menat494bd9e2022-03-28 18:52:46 +0530519 return frappe.desk.reportview.execute(
Sagar Vora9baa2222022-08-03 05:42:30 +0000520 doctype,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530521 filters=filter_list,
522 fields=["name", "parent_account"],
523 limit_start=start,
524 limit_page_length=page_len,
525 as_list=True,
526 )
527
Anand Doshifaefeaa2014-06-24 18:53:04 +0530528
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530529@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530530@frappe.validate_and_sanitize_search_inputs
Marica299e2172020-04-28 13:00:04 +0530531def get_blanket_orders(doctype, txt, searchfield, start, page_len, filters):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530532 return frappe.db.sql(
533 """select distinct bo.name, bo.blanket_order_type, bo.to_date
Marica299e2172020-04-28 13:00:04 +0530534 from `tabBlanket Order` bo, `tabBlanket Order Item` boi
535 where
536 boi.parent = bo.name
537 and boi.item_code = {item_code}
538 and bo.blanket_order_type = '{blanket_order_type}'
539 and bo.company = {company}
Ankush Menat494bd9e2022-03-28 18:52:46 +0530540 and bo.docstatus = 1""".format(
541 item_code=frappe.db.escape(filters.get("item")),
542 blanket_order_type=filters.get("blanket_order_type"),
543 company=frappe.db.escape(filters.get("company")),
544 )
545 )
Nabin Haitafd14f62015-10-19 11:55:28 +0530546
Himanshud94a38e2020-05-18 14:26:26 +0530547
Nabin Haitafd14f62015-10-19 11:55:28 +0530548@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530549@frappe.validate_and_sanitize_search_inputs
Nabin Haitafd14f62015-10-19 11:55:28 +0530550def get_income_account(doctype, txt, searchfield, start, page_len, filters):
551 from erpnext.controllers.queries import get_match_cond
552
553 # income account can be any Credit account,
554 # but can also be a Asset account with account_type='Income Account' in special circumstances.
555 # Hence the first condition is an "OR"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530556 if not filters:
557 filters = {}
Nabin Haitafd14f62015-10-19 11:55:28 +0530558
Sagar Vora9baa2222022-08-03 05:42:30 +0000559 doctype = "Account"
Anand Doshi21e09a22015-10-29 12:21:41 +0530560 condition = ""
Nabin Haitafd14f62015-10-19 11:55:28 +0530561 if filters.get("company"):
562 condition += "and tabAccount.company = %(company)s"
Anand Doshi21e09a22015-10-29 12:21:41 +0530563
Ankush Menat494bd9e2022-03-28 18:52:46 +0530564 return frappe.db.sql(
565 """select tabAccount.name from `tabAccount`
Nabin Haitafd14f62015-10-19 11:55:28 +0530566 where (tabAccount.report_type = "Profit and Loss"
567 or tabAccount.account_type in ("Income Account", "Temporary"))
568 and tabAccount.is_group=0
569 and tabAccount.`{key}` LIKE %(txt)s
Rushabh Mehta3574b372016-03-11 14:33:04 +0530570 {condition} {match_condition}
Ankush Menat494bd9e2022-03-28 18:52:46 +0530571 order by idx desc, name""".format(
572 condition=condition, match_condition=get_match_cond(doctype), key=searchfield
573 ),
574 {"txt": "%" + txt + "%", "company": filters.get("company", "")},
575 )
576
Nabin Hait3a15c922016-03-04 12:30:46 +0530577
Deepesh Garg96e874b2020-11-15 22:43:01 +0530578@frappe.whitelist()
579@frappe.validate_and_sanitize_search_inputs
580def get_filtered_dimensions(doctype, txt, searchfield, start, page_len, filters):
Chillar Anand915b3432021-09-02 16:44:59 +0530581 from erpnext.accounts.doctype.accounting_dimension_filter.accounting_dimension_filter import (
582 get_dimension_filter_map,
583 )
Ankush Menat494bd9e2022-03-28 18:52:46 +0530584
Deepesh Garg96e874b2020-11-15 22:43:01 +0530585 dimension_filters = get_dimension_filter_map()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530586 dimension_filters = dimension_filters.get((filters.get("dimension"), filters.get("account")))
Deepesh Garg6c17b842020-11-25 13:42:16 +0530587 query_filters = []
mergify[bot]071118f2021-11-30 13:15:20 +0000588 or_filters = []
Ankush Menat494bd9e2022-03-28 18:52:46 +0530589 fields = ["name"]
mergify[bot]071118f2021-11-30 13:15:20 +0000590
591 searchfields = frappe.get_meta(doctype).get_search_fields()
Deepesh Garg96e874b2020-11-15 22:43:01 +0530592
593 meta = frappe.get_meta(doctype)
Deepesh Garg96e874b2020-11-15 22:43:01 +0530594 if meta.is_tree:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530595 query_filters.append(["is_group", "=", 0])
Deepesh Garg96e874b2020-11-15 22:43:01 +0530596
Ankush Menat494bd9e2022-03-28 18:52:46 +0530597 if meta.has_field("disabled"):
598 query_filters.append(["disabled", "!=", 1])
Subin Tom333e44e2021-08-18 16:17:54 +0530599
Ankush Menat494bd9e2022-03-28 18:52:46 +0530600 if meta.has_field("company"):
601 query_filters.append(["company", "=", filters.get("company")])
Deepesh Garg6c17b842020-11-25 13:42:16 +0530602
mergify[bot]071118f2021-11-30 13:15:20 +0000603 for field in searchfields:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530604 or_filters.append([field, "LIKE", "%%%s%%" % txt])
mergify[bot]071118f2021-11-30 13:15:20 +0000605 fields.append(field)
Deepesh Garg96e874b2020-11-15 22:43:01 +0530606
607 if dimension_filters:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530608 if dimension_filters["allow_or_restrict"] == "Allow":
609 query_selector = "in"
Deepesh Garg96e874b2020-11-15 22:43:01 +0530610 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530611 query_selector = "not in"
Deepesh Garg96e874b2020-11-15 22:43:01 +0530612
Ankush Menat494bd9e2022-03-28 18:52:46 +0530613 if len(dimension_filters["allowed_dimensions"]) == 1:
614 dimensions = tuple(dimension_filters["allowed_dimensions"] * 2)
Deepesh Garg96e874b2020-11-15 22:43:01 +0530615 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530616 dimensions = tuple(dimension_filters["allowed_dimensions"])
Deepesh Garg96e874b2020-11-15 22:43:01 +0530617
Ankush Menat494bd9e2022-03-28 18:52:46 +0530618 query_filters.append(["name", query_selector, dimensions])
Deepesh Garg96e874b2020-11-15 22:43:01 +0530619
Ankush Menat494bd9e2022-03-28 18:52:46 +0530620 output = frappe.get_list(
621 doctype, fields=fields, filters=query_filters, or_filters=or_filters, as_list=1
622 )
Deepesh Garg6c17b842020-11-25 13:42:16 +0530623
mergify[bot]071118f2021-11-30 13:15:20 +0000624 return [tuple(d) for d in set(output)]
Nabin Hait3a15c922016-03-04 12:30:46 +0530625
Ankush Menat494bd9e2022-03-28 18:52:46 +0530626
Nabin Hait3a15c922016-03-04 12:30:46 +0530627@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530628@frappe.validate_and_sanitize_search_inputs
Nabin Hait3a15c922016-03-04 12:30:46 +0530629def get_expense_account(doctype, txt, searchfield, start, page_len, filters):
630 from erpnext.controllers.queries import get_match_cond
Rushabh Mehta203cc962016-04-07 15:25:43 +0530631
Ankush Menat494bd9e2022-03-28 18:52:46 +0530632 if not filters:
633 filters = {}
Nabin Hait3a15c922016-03-04 12:30:46 +0530634
Sagar Vora9baa2222022-08-03 05:42:30 +0000635 doctype = "Account"
Nabin Hait3a15c922016-03-04 12:30:46 +0530636 condition = ""
637 if filters.get("company"):
638 condition += "and tabAccount.company = %(company)s"
Rushabh Mehta203cc962016-04-07 15:25:43 +0530639
Ankush Menat494bd9e2022-03-28 18:52:46 +0530640 return frappe.db.sql(
641 """select tabAccount.name from `tabAccount`
Nabin Hait3a15c922016-03-04 12:30:46 +0530642 where (tabAccount.report_type = "Profit and Loss"
Mangesh-Khairnar5619db22019-08-21 14:49:24 +0530643 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 +0530644 and tabAccount.is_group=0
645 and tabAccount.docstatus!=2
646 and tabAccount.{key} LIKE %(txt)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530647 {condition} {match_condition}""".format(
648 condition=condition, key=searchfield, match_condition=get_match_cond(doctype)
649 ),
650 {"company": filters.get("company", ""), "txt": "%" + txt + "%"},
651 )
suyashphadtare049a88c2017-01-12 17:49:37 +0530652
653
654@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530655@frappe.validate_and_sanitize_search_inputs
suyashphadtare049a88c2017-01-12 17:49:37 +0530656def warehouse_query(doctype, txt, searchfield, start, page_len, filters):
657 # Should be used when item code is passed in filters.
Sagar Vora9baa2222022-08-03 05:42:30 +0000658 doctype = "Warehouse"
suyashphadtare750a0672017-01-18 15:35:01 +0530659 conditions, bin_conditions = [], []
660 filter_dict = get_doctype_wise_filters(filters)
661
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530662 query = """select `tabWarehouse`.name,
Conor74a782d2022-06-17 06:31:27 -0500663 CONCAT_WS(' : ', 'Actual Qty', ifnull(round(`tabBin`.actual_qty, 2), 0 )) actual_qty
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530664 from `tabWarehouse` left join `tabBin`
665 on `tabBin`.warehouse = `tabWarehouse`.name {bin_conditions}
suyashphadtare34ab1362017-01-31 15:14:44 +0530666 where
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530667 `tabWarehouse`.`{key}` like {txt}
suyashphadtare34ab1362017-01-31 15:14:44 +0530668 {fcond} {mcond}
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530669 order by ifnull(`tabBin`.actual_qty, 0) desc
suyashphadtare34ab1362017-01-31 15:14:44 +0530670 limit
Conor00ef4992022-06-14 00:19:07 -0500671 {page_len} offset {start}
suyashphadtare34ab1362017-01-31 15:14:44 +0530672 """.format(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530673 bin_conditions=get_filters_cond(
674 doctype, filter_dict.get("Bin"), bin_conditions, ignore_permissions=True
675 ),
676 key=searchfield,
677 fcond=get_filters_cond(doctype, filter_dict.get("Warehouse"), conditions),
678 mcond=get_match_cond(doctype),
679 start=start,
680 page_len=page_len,
681 txt=frappe.db.escape("%{0}%".format(txt)),
682 )
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530683
684 return frappe.db.sql(query)
suyashphadtare750a0672017-01-18 15:35:01 +0530685
686
687def get_doctype_wise_filters(filters):
688 # Helper function to seperate filters doctype_wise
689 filter_dict = defaultdict(list)
690 for row in filters:
691 filter_dict[row[0]].append(row)
692 return filter_dict
tundebabzy2a4fefc2017-11-29 06:23:09 +0100693
694
695@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530696@frappe.validate_and_sanitize_search_inputs
tundebabzy2a4fefc2017-11-29 06:23:09 +0100697def get_batch_numbers(doctype, txt, searchfield, start, page_len, filters):
rohitwaghchaure9fbed562018-01-12 16:22:33 +0530698 query = """select batch_id from `tabBatch`
Doridel Cahanap59e4c322018-08-06 17:15:18 +0800699 where disabled = 0
Conorb8f728a2022-06-15 01:37:33 -0500700 and (expiry_date >= CURRENT_DATE or expiry_date IS NULL)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530701 and name like {txt}""".format(
702 txt=frappe.db.escape("%{0}%".format(txt))
703 )
tundebabzy2a4fefc2017-11-29 06:23:09 +0100704
Ankush Menat494bd9e2022-03-28 18:52:46 +0530705 if filters and filters.get("item"):
706 query += " and item = {item}".format(item=frappe.db.escape(filters.get("item")))
tundebabzy2a4fefc2017-11-29 06:23:09 +0100707
Sachin Mane64f48db2018-01-08 17:57:32 +0530708 return frappe.db.sql(query, filters)
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530709
Himanshud94a38e2020-05-18 14:26:26 +0530710
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530711@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530712@frappe.validate_and_sanitize_search_inputs
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530713def item_manufacturer_query(doctype, txt, searchfield, start, page_len, filters):
Maricabac4b932019-09-16 19:44:28 +0530714 item_filters = [
Ankush Menat494bd9e2022-03-28 18:52:46 +0530715 ["manufacturer", "like", "%" + txt + "%"],
716 ["item_code", "=", filters.get("item_code")],
Maricabac4b932019-09-16 19:44:28 +0530717 ]
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530718
Maricabac4b932019-09-16 19:44:28 +0530719 item_manufacturers = frappe.get_all(
720 "Item Manufacturer",
721 fields=["manufacturer", "manufacturer_part_no"],
722 filters=item_filters,
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530723 limit_start=start,
724 limit_page_length=page_len,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530725 as_list=1,
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530726 )
Maricabac4b932019-09-16 19:44:28 +0530727 return item_manufacturers
Saqibd9956092019-11-18 11:46:55 +0530728
Himanshud94a38e2020-05-18 14:26:26 +0530729
Saqibd9956092019-11-18 11:46:55 +0530730@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530731@frappe.validate_and_sanitize_search_inputs
Saqibd9956092019-11-18 11:46:55 +0530732def get_purchase_receipts(doctype, txt, searchfield, start, page_len, filters):
733 query = """
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530734 select pr.name
Saqibd9956092019-11-18 11:46:55 +0530735 from `tabPurchase Receipt` pr, `tabPurchase Receipt Item` pritem
736 where pr.docstatus = 1 and pritem.parent = pr.name
Ankush Menat494bd9e2022-03-28 18:52:46 +0530737 and pr.name like {txt}""".format(
738 txt=frappe.db.escape("%{0}%".format(txt))
739 )
Saqibd9956092019-11-18 11:46:55 +0530740
Ankush Menat494bd9e2022-03-28 18:52:46 +0530741 if filters and filters.get("item_code"):
742 query += " and pritem.item_code = {item_code}".format(
743 item_code=frappe.db.escape(filters.get("item_code"))
744 )
Saqibd9956092019-11-18 11:46:55 +0530745
746 return frappe.db.sql(query, filters)
747
Himanshud94a38e2020-05-18 14:26:26 +0530748
Saqibd9956092019-11-18 11:46:55 +0530749@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530750@frappe.validate_and_sanitize_search_inputs
Saqibd9956092019-11-18 11:46:55 +0530751def get_purchase_invoices(doctype, txt, searchfield, start, page_len, filters):
752 query = """
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530753 select pi.name
Saqibd9956092019-11-18 11:46:55 +0530754 from `tabPurchase Invoice` pi, `tabPurchase Invoice Item` piitem
755 where pi.docstatus = 1 and piitem.parent = pi.name
Ankush Menat494bd9e2022-03-28 18:52:46 +0530756 and pi.name like {txt}""".format(
757 txt=frappe.db.escape("%{0}%".format(txt))
758 )
Saqibd9956092019-11-18 11:46:55 +0530759
Ankush Menat494bd9e2022-03-28 18:52:46 +0530760 if filters and filters.get("item_code"):
761 query += " and piitem.item_code = {item_code}".format(
762 item_code=frappe.db.escape(filters.get("item_code"))
763 )
Saqibd9956092019-11-18 11:46:55 +0530764
765 return frappe.db.sql(query, filters)
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530766
Himanshud94a38e2020-05-18 14:26:26 +0530767
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530768@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530769@frappe.validate_and_sanitize_search_inputs
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530770def get_tax_template(doctype, txt, searchfield, start, page_len, filters):
771
Ankush Menat494bd9e2022-03-28 18:52:46 +0530772 item_doc = frappe.get_cached_doc("Item", filters.get("item_code"))
773 item_group = filters.get("item_group")
774 company = filters.get("company")
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530775 taxes = item_doc.taxes or []
776
777 while item_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530778 item_group_doc = frappe.get_cached_doc("Item Group", item_group)
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530779 taxes += item_group_doc.taxes or []
780 item_group = item_group_doc.parent_item_group
781
782 if not taxes:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530783 return frappe.get_all(
784 "Item Tax Template", filters={"disabled": 0, "company": company}, as_list=True
785 )
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530786 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530787 valid_from = filters.get("valid_from")
Marica0fcb05a2020-08-10 14:48:13 +0530788 valid_from = valid_from[1] if isinstance(valid_from, list) else valid_from
789
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530790 args = {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530791 "item_code": filters.get("item_code"),
792 "posting_date": valid_from,
793 "tax_category": filters.get("tax_category"),
794 "company": company,
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530795 }
796
797 taxes = _get_item_tax_template(args, taxes, for_validate=True)
798 return [(d,) for d in set(taxes)]
Himanshud94a38e2020-05-18 14:26:26 +0530799
800
Ankush Menat7eac4a22021-04-19 10:33:39 +0530801def get_fields(doctype, fields=None):
802 if fields is None:
803 fields = []
Himanshud94a38e2020-05-18 14:26:26 +0530804 meta = frappe.get_meta(doctype)
805 fields.extend(meta.get_search_fields())
806
807 if meta.title_field and not meta.title_field.strip() in fields:
808 fields.insert(1, meta.title_field.strip())
809
810 return unique(fields)