blob: f1cef71452f62236fd9ce27e184720c654131a95 [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
HarryPauloe12e3bb2023-05-13 23:38:47 -030056 searchfields = frappe.get_meta(doctype).get_search_fields()
57 searchfields = " or ".join(field + " like %(txt)s" for field in searchfields)
58
Ankush Menat494bd9e2022-03-28 18:52:46 +053059 return frappe.db.sql(
60 """select {fields} from `tabLead`
Anand Doshibd67e872014-04-11 16:51:27 +053061 where docstatus < 2
62 and ifnull(status, '') != 'Converted'
Anand Doshi48d3b542014-07-09 13:15:03 +053063 and ({key} like %(txt)s
64 or lead_name like %(txt)s
HarryPauloe12e3bb2023-05-13 23:38:47 -030065 or company_name like %(txt)s
66 or {scond})
Anand Doshi48d3b542014-07-09 13:15:03 +053067 {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +053068 order by
Conorea28ed12022-06-17 10:47:48 -050069 (case when locate(%(_txt)s, name) > 0 then locate(%(_txt)s, name) else 99999 end),
70 (case when locate(%(_txt)s, lead_name) > 0 then locate(%(_txt)s, lead_name) else 99999 end),
71 (case when locate(%(_txt)s, company_name) > 0 then locate(%(_txt)s, company_name) else 99999 end),
Rushabh Mehta3574b372016-03-11 14:33:04 +053072 idx desc,
Anand Doshi652bc072014-04-16 15:21:46 +053073 name, lead_name
Conor00ef4992022-06-14 00:19:07 -050074 limit %(page_len)s offset %(start)s""".format(
HarryPauloe12e3bb2023-05-13 23:38:47 -030075 **{
76 "fields": ", ".join(fields),
77 "key": searchfield,
78 "scond": searchfields,
79 "mcond": get_match_cond(doctype),
80 }
Ankush Menat494bd9e2022-03-28 18:52:46 +053081 ),
82 {"txt": "%%%s%%" % txt, "_txt": txt.replace("%", ""), "start": start, "page_len": page_len},
83 )
84
85 # searches for customer
Saurabh02875592013-07-08 18:45:55 +053086
Himanshud94a38e2020-05-18 14:26:26 +053087
Chinmay D. Paiaa121092020-07-01 21:14:32 +053088@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +053089@frappe.validate_and_sanitize_search_inputs
Rohit Waghchaure5f849932022-10-24 16:10:47 +053090def customer_query(doctype, txt, searchfield, start, page_len, filters, as_dict=False):
Sagar Vora9baa2222022-08-03 05:42:30 +000091 doctype = "Customer"
KanchanChauhan4b888b92017-07-25 14:03:01 +053092 conditions = []
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053093 cust_master_name = frappe.defaults.get_user_default("cust_master_name")
Saurabhf52dc072013-07-10 13:07:49 +053094
Rohit Waghchaure46d148d2022-10-24 15:48:34 +053095 fields = ["name"]
96 if cust_master_name != "Customer Name":
Rohit Waghchaureb0fc5682022-11-03 11:24:58 +053097 fields.append("customer_name")
Rushabh Mehtab92087c2017-01-13 18:53:11 +053098
Sagar Vora9baa2222022-08-03 05:42:30 +000099 fields = get_fields(doctype, fields)
Sagar Vora9baa2222022-08-03 05:42:30 +0000100 searchfields = frappe.get_meta(doctype).get_search_fields()
Ankush Menata9c84f72021-06-11 16:00:48 +0530101 searchfields = " or ".join(field + " like %(txt)s" for field in searchfields)
Saurabh02875592013-07-08 18:45:55 +0530102
Ankush Menat494bd9e2022-03-28 18:52:46 +0530103 return frappe.db.sql(
104 """select {fields} from `tabCustomer`
Anand Doshibd67e872014-04-11 16:51:27 +0530105 where docstatus < 2
Console Admin86231662017-06-23 20:32:52 +0300106 and ({scond}) and disabled=0
KanchanChauhan4b888b92017-07-25 14:03:01 +0530107 {fcond} {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +0530108 order by
Conorea28ed12022-06-17 10:47:48 -0500109 (case when locate(%(_txt)s, name) > 0 then locate(%(_txt)s, name) else 99999 end),
110 (case when locate(%(_txt)s, customer_name) > 0 then locate(%(_txt)s, customer_name) else 99999 end),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530111 idx desc,
Anand Doshibd67e872014-04-11 16:51:27 +0530112 name, customer_name
Conor00ef4992022-06-14 00:19:07 -0500113 limit %(page_len)s offset %(start)s""".format(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530114 **{
115 "fields": ", ".join(fields),
116 "scond": searchfields,
117 "mcond": get_match_cond(doctype),
118 "fcond": get_filters_cond(doctype, filters, conditions).replace("%", "%%"),
119 }
120 ),
121 {"txt": "%%%s%%" % txt, "_txt": txt.replace("%", ""), "start": start, "page_len": page_len},
Rohit Waghchaure5f849932022-10-24 16:10:47 +0530122 as_dict=as_dict,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530123 )
Saurabh02875592013-07-08 18:45:55 +0530124
Himanshud94a38e2020-05-18 14:26:26 +0530125
Saurabh02875592013-07-08 18:45:55 +0530126# searches for supplier
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530127@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530128@frappe.validate_and_sanitize_search_inputs
Rohit Waghchaure5f849932022-10-24 16:10:47 +0530129def supplier_query(doctype, txt, searchfield, start, page_len, filters, as_dict=False):
Sagar Vora9baa2222022-08-03 05:42:30 +0000130 doctype = "Supplier"
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530131 supp_master_name = frappe.defaults.get_user_default("supp_master_name")
Suraj Shetty1923ef02020-08-05 19:42:25 +0530132
Rohit Waghchaure46d148d2022-10-24 15:48:34 +0530133 fields = ["name"]
134 if supp_master_name != "Supplier Name":
Rohit Waghchaureb0fc5682022-11-03 11:24:58 +0530135 fields.append("supplier_name")
Himanshud94a38e2020-05-18 14:26:26 +0530136
Sagar Vora9baa2222022-08-03 05:42:30 +0000137 fields = get_fields(doctype, fields)
Saurabh02875592013-07-08 18:45:55 +0530138
Ankush Menat494bd9e2022-03-28 18:52:46 +0530139 return frappe.db.sql(
140 """select {field} from `tabSupplier`
Anand Doshibd67e872014-04-11 16:51:27 +0530141 where docstatus < 2
Anand Doshi48d3b542014-07-09 13:15:03 +0530142 and ({key} like %(txt)s
Ankush Menat2221c9e2021-10-27 19:15:44 +0530143 or supplier_name like %(txt)s) and disabled=0
Conorea28ed12022-06-17 10:47:48 -0500144 and (on_hold = 0 or (on_hold = 1 and CURRENT_DATE > release_date))
Anand Doshi48d3b542014-07-09 13:15:03 +0530145 {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +0530146 order by
Conorea28ed12022-06-17 10:47:48 -0500147 (case when locate(%(_txt)s, name) > 0 then locate(%(_txt)s, name) else 99999 end),
148 (case when locate(%(_txt)s, supplier_name) > 0 then locate(%(_txt)s, supplier_name) else 99999 end),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530149 idx desc,
Anand Doshibd67e872014-04-11 16:51:27 +0530150 name, supplier_name
Conor00ef4992022-06-14 00:19:07 -0500151 limit %(page_len)s offset %(start)s""".format(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530152 **{"field": ", ".join(fields), "key": searchfield, "mcond": get_match_cond(doctype)}
153 ),
154 {"txt": "%%%s%%" % txt, "_txt": txt.replace("%", ""), "start": start, "page_len": page_len},
Rohit Waghchaure5f849932022-10-24 16:10:47 +0530155 as_dict=as_dict,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530156 )
Anand Doshibd67e872014-04-11 16:51:27 +0530157
Himanshud94a38e2020-05-18 14:26:26 +0530158
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530159@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530160@frappe.validate_and_sanitize_search_inputs
Nabin Hait9a380ef2013-07-16 17:24:17 +0530161def tax_account_query(doctype, txt, searchfield, start, page_len, filters):
Sagar Vora9baa2222022-08-03 05:42:30 +0000162 doctype = "Account"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530163 company_currency = erpnext.get_company_currency(filters.get("company"))
Deepesh Gargfbf6e562020-03-31 10:45:32 +0530164
Suraj Shetty1923ef02020-08-05 19:42:25 +0530165 def get_accounts(with_account_type_filter):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530166 account_type_condition = ""
Suraj Shetty1923ef02020-08-05 19:42:25 +0530167 if with_account_type_filter:
168 account_type_condition = "AND account_type in %(account_types)s"
169
Ankush Menat494bd9e2022-03-28 18:52:46 +0530170 accounts = frappe.db.sql(
171 """
Suraj Shetty1923ef02020-08-05 19:42:25 +0530172 SELECT name, parent_account
173 FROM `tabAccount`
174 WHERE `tabAccount`.docstatus!=2
175 {account_type_condition}
176 AND is_group = 0
177 AND company = %(company)s
Saqib Ansaria1e3ae82022-05-11 13:01:06 +0530178 AND disabled = %(disabled)s
Deepesh Garg57924592022-03-22 18:26:58 +0530179 AND (account_currency = %(currency)s or ifnull(account_currency, '') = '')
Suraj Shetty1923ef02020-08-05 19:42:25 +0530180 AND `{searchfield}` LIKE %(txt)s
prssannade7a2bc2020-09-21 13:57:04 +0530181 {mcond}
Suraj Shetty1923ef02020-08-05 19:42:25 +0530182 ORDER BY idx DESC, name
Conor00ef4992022-06-14 00:19:07 -0500183 LIMIT %(limit)s offset %(offset)s
prssannade7a2bc2020-09-21 13:57:04 +0530184 """.format(
185 account_type_condition=account_type_condition,
186 searchfield=searchfield,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530187 mcond=get_match_cond(doctype),
prssannade7a2bc2020-09-21 13:57:04 +0530188 ),
Suraj Shetty1923ef02020-08-05 19:42:25 +0530189 dict(
190 account_types=filters.get("account_type"),
191 company=filters.get("company"),
Saqib Ansaria1e3ae82022-05-11 13:01:06 +0530192 disabled=filters.get("disabled", 0),
Suraj Shetty1923ef02020-08-05 19:42:25 +0530193 currency=company_currency,
194 txt="%{}%".format(txt),
195 offset=start,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530196 limit=page_len,
197 ),
Suraj Shetty1923ef02020-08-05 19:42:25 +0530198 )
199
200 return accounts
201
202 tax_accounts = get_accounts(True)
203
Nabin Hait0c21e2a2014-03-21 11:14:49 +0530204 if not tax_accounts:
Suraj Shetty1923ef02020-08-05 19:42:25 +0530205 tax_accounts = get_accounts(False)
Anand Doshibd67e872014-04-11 16:51:27 +0530206
Nabin Hait0c21e2a2014-03-21 11:14:49 +0530207 return tax_accounts
Saurabh02875592013-07-08 18:45:55 +0530208
Himanshud94a38e2020-05-18 14:26:26 +0530209
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530210@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530211@frappe.validate_and_sanitize_search_inputs
Rushabh Mehta203cc962016-04-07 15:25:43 +0530212def item_query(doctype, txt, searchfield, start, page_len, filters, as_dict=False):
Sagar Vora9baa2222022-08-03 05:42:30 +0000213 doctype = "Item"
Saurabh02875592013-07-08 18:45:55 +0530214 conditions = []
Saurabhf52dc072013-07-10 13:07:49 +0530215
rohitwaghchaurec59371a2021-06-03 20:02:58 +0530216 if isinstance(filters, str):
217 filters = json.loads(filters)
218
Ankush Menat494bd9e2022-03-28 18:52:46 +0530219 # Get searchfields from meta and use in Item Link field query
Sagar Vora9baa2222022-08-03 05:42:30 +0000220 meta = frappe.get_meta(doctype, cached=True)
marination3dbef9d2019-10-28 15:48:10 +0530221 searchfields = meta.get_search_fields()
222
Ankush Menat494bd9e2022-03-28 18:52:46 +0530223 columns = ""
Rohit Waghchaurefd889fd2022-09-28 23:00:45 +0530224 extra_searchfields = [field for field in searchfields if not field in ["name", "description"]]
Rohit Waghchaurec42312e2019-11-19 19:05:23 +0530225
226 if extra_searchfields:
Rohit Waghchaurefd889fd2022-09-28 23:00:45 +0530227 columns += ", " + ", ".join(extra_searchfields)
228
229 if "description" in searchfields:
230 columns += """, if(length(tabItem.description) > 40, \
231 concat(substr(tabItem.description, 1, 40), "..."), description) as description"""
marination1e754b12019-10-30 18:33:44 +0530232
Ankush Menat494bd9e2022-03-28 18:52:46 +0530233 searchfields = searchfields + [
234 field
235 for field in [searchfield or "name", "item_code", "item_group", "item_name"]
236 if not field in searchfields
237 ]
marination3dbef9d2019-10-28 15:48:10 +0530238 searchfields = " or ".join([field + " like %(txt)s" for field in searchfields])
239
DeeMysterioaa826242021-09-14 13:58:18 +0530240 if filters and isinstance(filters, dict):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530241 if filters.get("customer") or filters.get("supplier"):
242 party = filters.get("customer") or filters.get("supplier")
243 item_rules_list = frappe.get_all(
244 "Party Specific Item", filters={"party": party}, fields=["restrict_based_on", "based_on_value"]
245 )
Rohit Waghchaure721b4132021-06-02 14:13:09 +0530246
DeeMysterioaa826242021-09-14 13:58:18 +0530247 filters_dict = {}
248 for rule in item_rules_list:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530249 if rule["restrict_based_on"] == "Item":
250 rule["restrict_based_on"] = "name"
DeeMysterioaa826242021-09-14 13:58:18 +0530251 filters_dict[rule.restrict_based_on] = []
noahjacobca2fb472021-05-12 16:25:07 +0530252
DeeMysterioaa826242021-09-14 13:58:18 +0530253 for rule in item_rules_list:
254 filters_dict[rule.restrict_based_on].append(rule.based_on_value)
noahjacobca2fb472021-05-12 16:25:07 +0530255
DeeMysterioaa826242021-09-14 13:58:18 +0530256 for filter in filters_dict:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530257 filters[scrub(filter)] = ["in", filters_dict[filter]]
DeeMysterioaa826242021-09-14 13:58:18 +0530258
Ankush Menat494bd9e2022-03-28 18:52:46 +0530259 if filters.get("customer"):
260 del filters["customer"]
DeeMysterioaa826242021-09-14 13:58:18 +0530261 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530262 del filters["supplier"]
Ankush Menat41a95e52022-02-03 13:02:13 +0530263 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530264 filters.pop("customer", None)
265 filters.pop("supplier", None)
DeeMysterioaa826242021-09-14 13:58:18 +0530266
Ankush Menat494bd9e2022-03-28 18:52:46 +0530267 description_cond = ""
Sagar Vora9baa2222022-08-03 05:42:30 +0000268 if frappe.db.count(doctype, cache=True) < 50000:
Rushabh Mehtad5f9ebd2018-04-02 23:37:33 +0530269 # scan description only if items are less than 50000
Ankush Menat494bd9e2022-03-28 18:52:46 +0530270 description_cond = "or tabItem.description LIKE %(txt)s"
Rohit Waghchaurefd889fd2022-09-28 23:00:45 +0530271
Ankush Menat494bd9e2022-03-28 18:52:46 +0530272 return frappe.db.sql(
273 """select
Rohit Waghchaurefd889fd2022-09-28 23:00:45 +0530274 tabItem.name {columns}
Anand Doshibd67e872014-04-11 16:51:27 +0530275 from tabItem
Anand Doshi22c0d782013-11-04 16:23:04 +0530276 where tabItem.docstatus < 2
Anand Doshi21e09a22015-10-29 12:21:41 +0530277 and tabItem.disabled=0
rohitwaghchaure79789072020-05-21 18:10:13 +0530278 and tabItem.has_variants=0
Rushabh Mehta864d1ea2014-06-23 12:20:12 +0530279 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 +0530280 and ({scond} or tabItem.item_code IN (select parent from `tabItem Barcode` where barcode LIKE %(txt)s)
Rohit Waghchaure2bfb0632019-03-02 21:47:55 +0530281 {description_cond})
Anand Doshi22c0d782013-11-04 16:23:04 +0530282 {fcond} {mcond}
Anand Doshi652bc072014-04-16 15:21:46 +0530283 order by
284 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
285 if(locate(%(_txt)s, item_name), locate(%(_txt)s, item_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530286 idx desc,
Anand Doshi652bc072014-04-16 15:21:46 +0530287 name, item_name
Rushabh Mehtabc4e2cd2017-10-17 12:30:34 +0530288 limit %(start)s, %(page_len)s """.format(
marination1e754b12019-10-30 18:33:44 +0530289 columns=columns,
marination3dbef9d2019-10-28 15:48:10 +0530290 scond=searchfields,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530291 fcond=get_filters_cond(doctype, filters, conditions).replace("%", "%%"),
292 mcond=get_match_cond(doctype).replace("%", "%%"),
293 description_cond=description_cond,
294 ),
295 {
296 "today": nowdate(),
297 "txt": "%%%s%%" % txt,
298 "_txt": txt.replace("%", ""),
299 "start": start,
300 "page_len": page_len,
301 },
302 as_dict=as_dict,
303 )
Saurabh02875592013-07-08 18:45:55 +0530304
Himanshud94a38e2020-05-18 14:26:26 +0530305
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530306@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530307@frappe.validate_and_sanitize_search_inputs
Saurabh022ab632017-11-10 15:06:02 +0530308def bom(doctype, txt, searchfield, start, page_len, filters):
Sagar Vora9baa2222022-08-03 05:42:30 +0000309 doctype = "BOM"
Anand Doshibd67e872014-04-11 16:51:27 +0530310 conditions = []
Sagar Vora9baa2222022-08-03 05:42:30 +0000311 fields = get_fields(doctype, ["name", "item"])
Saurabhf52dc072013-07-10 13:07:49 +0530312
Ankush Menat494bd9e2022-03-28 18:52:46 +0530313 return frappe.db.sql(
314 """select {fields}
Conorea28ed12022-06-17 10:47:48 -0500315 from `tabBOM`
316 where `tabBOM`.docstatus=1
317 and `tabBOM`.is_active=1
318 and `tabBOM`.`{key}` like %(txt)s
Nabin Hait62211172016-03-16 16:22:03 +0530319 {fcond} {mcond}
320 order by
Conorea28ed12022-06-17 10:47:48 -0500321 (case when locate(%(_txt)s, name) > 0 then locate(%(_txt)s, name) else 99999 end),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530322 idx desc, name
Conorea28ed12022-06-17 10:47:48 -0500323 limit %(page_len)s offset %(start)s""".format(
Himanshud94a38e2020-05-18 14:26:26 +0530324 fields=", ".join(fields),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530325 fcond=get_filters_cond(doctype, filters, conditions).replace("%", "%%"),
326 mcond=get_match_cond(doctype).replace("%", "%%"),
327 key=searchfield,
328 ),
Mangesh-Khairnar6a796912019-07-08 10:40:40 +0530329 {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530330 "txt": "%" + txt + "%",
331 "_txt": txt.replace("%", ""),
332 "start": start or 0,
333 "page_len": page_len or 20,
334 },
335 )
Saurabh02875592013-07-08 18:45:55 +0530336
Himanshud94a38e2020-05-18 14:26:26 +0530337
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530338@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530339@frappe.validate_and_sanitize_search_inputs
Saurabh02875592013-07-08 18:45:55 +0530340def get_project_name(doctype, txt, searchfield, start, page_len, filters):
Sagar Vora9baa2222022-08-03 05:42:30 +0000341 doctype = "Project"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530342 cond = ""
343 if filters and filters.get("customer"):
Suraj Shetty6ea3de92018-09-26 18:15:53 +0530344 cond = """(`tabProject`.customer = %s or
Ankush Menat494bd9e2022-03-28 18:52:46 +0530345 ifnull(`tabProject`.customer,"")="") and""" % (
346 frappe.db.escape(filters.get("customer"))
347 )
Anand Doshibd67e872014-04-11 16:51:27 +0530348
Sagar Vora9baa2222022-08-03 05:42:30 +0000349 fields = get_fields(doctype, ["name", "project_name"])
350 searchfields = frappe.get_meta(doctype).get_search_fields()
Conor74a782d2022-06-17 06:31:27 -0500351 searchfields = " or ".join(["`tabProject`." + field + " like %(txt)s" for field in searchfields])
Himanshud94a38e2020-05-18 14:26:26 +0530352
Ankush Menat494bd9e2022-03-28 18:52:46 +0530353 return frappe.db.sql(
354 """select {fields} from `tabProject`
Rucha Mahabal062d3012021-05-07 13:31:14 +0530355 where
Conor74a782d2022-06-17 06:31:27 -0500356 `tabProject`.status not in ('Completed', 'Cancelled')
Subin Tom889140f2021-06-22 16:26:19 +0530357 and {cond} {scond} {match_cond}
Rushabh Mehta3574b372016-03-11 14:33:04 +0530358 order by
Conorea28ed12022-06-17 10:47:48 -0500359 (case when locate(%(_txt)s, `tabProject`.name) > 0 then locate(%(_txt)s, `tabProject`.name) else 99999 end),
360 `tabProject`.idx desc,
Rushabh Mehta3574b372016-03-11 14:33:04 +0530361 `tabProject`.name asc
Conor00ef4992022-06-14 00:19:07 -0500362 limit {page_len} offset {start}""".format(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530363 fields=", ".join(["`tabProject`.{0}".format(f) for f in fields]),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530364 cond=cond,
Rucha Mahabal062d3012021-05-07 13:31:14 +0530365 scond=searchfields,
Rushabh Mehta3574b372016-03-11 14:33:04 +0530366 match_cond=get_match_cond(doctype),
367 start=start,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530368 page_len=page_len,
369 ),
370 {"txt": "%{0}%".format(txt), "_txt": txt.replace("%", "")},
371 )
Anand Doshibd67e872014-04-11 16:51:27 +0530372
tundebabzyf6d738b2017-09-18 12:40:09 +0100373
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530374@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530375@frappe.validate_and_sanitize_search_inputs
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530376def get_delivery_notes_to_be_billed(doctype, txt, searchfield, start, page_len, filters, as_dict):
Sagar Vora9baa2222022-08-03 05:42:30 +0000377 doctype = "Delivery Note"
378 fields = get_fields(doctype, ["name", "customer", "posting_date"])
Himanshud94a38e2020-05-18 14:26:26 +0530379
Ankush Menat494bd9e2022-03-28 18:52:46 +0530380 return frappe.db.sql(
381 """
Himanshud94a38e2020-05-18 14:26:26 +0530382 select %(fields)s
Anand Doshibd67e872014-04-11 16:51:27 +0530383 from `tabDelivery Note`
384 where `tabDelivery Note`.`%(key)s` like %(txt)s and
tundebabzyf6d738b2017-09-18 12:40:09 +0100385 `tabDelivery Note`.docstatus = 1
Conor74a782d2022-06-17 06:31:27 -0500386 and status not in ('Stopped', 'Closed') %(fcond)s
tundebabzyf6d738b2017-09-18 12:40:09 +0100387 and (
388 (`tabDelivery Note`.is_return = 0 and `tabDelivery Note`.per_billed < 100)
Deepesh Garge2dc1022021-04-14 11:21:11 +0530389 or (`tabDelivery Note`.grand_total = 0 and `tabDelivery Note`.per_billed < 100)
tundebabzyf6d738b2017-09-18 12:40:09 +0100390 or (
391 `tabDelivery Note`.is_return = 1
392 and return_against in (select name from `tabDelivery Note` where per_billed < 100)
393 )
394 )
Conor00ef4992022-06-14 00:19:07 -0500395 %(mcond)s order by `tabDelivery Note`.`%(key)s` asc limit %(page_len)s offset %(start)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530396 """
397 % {
398 "fields": ", ".join(["`tabDelivery Note`.{0}".format(f) for f in fields]),
399 "key": searchfield,
400 "fcond": get_filters_cond(doctype, filters, []),
401 "mcond": get_match_cond(doctype),
402 "start": start,
403 "page_len": page_len,
404 "txt": "%(txt)s",
405 },
406 {"txt": ("%%%s%%" % txt)},
407 as_dict=as_dict,
408 )
tundebabzyf6d738b2017-09-18 12:40:09 +0100409
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530410
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530411@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530412@frappe.validate_and_sanitize_search_inputs
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530413def get_batch_no(doctype, txt, searchfield, start, page_len, filters):
Sagar Vora9baa2222022-08-03 05:42:30 +0000414 doctype = "Batch"
Neil Trini Lasradoebb60f52015-07-08 14:36:09 +0530415 cond = ""
416 if filters.get("posting_date"):
Nabin Hait7918b922018-01-31 15:30:03 +0530417 cond = "and (batch.expiry_date is null or batch.expiry_date >= %(posting_date)s)"
Rushabh Mehtab6398be2015-08-26 10:50:16 +0530418
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530419 batch_nos = None
420 args = {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530421 "item_code": filters.get("item_code"),
422 "warehouse": filters.get("warehouse"),
423 "posting_date": filters.get("posting_date"),
424 "txt": "%{0}%".format(txt),
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530425 "start": start,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530426 "page_len": page_len,
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530427 }
428
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530429 having_clause = "having sum(sle.actual_qty) > 0"
430 if filters.get("is_return"):
431 having_clause = ""
432
Sagar Vora9baa2222022-08-03 05:42:30 +0000433 meta = frappe.get_meta(doctype, cached=True)
Deepesh Garga0d192e2020-09-22 13:54:07 +0530434 searchfields = meta.get_search_fields()
435
Ankush Menat494bd9e2022-03-28 18:52:46 +0530436 search_columns = ""
437 search_cond = ""
Deepesh Gargf58a5ec2020-10-05 13:55:53 +0530438
Deepesh Garga0d192e2020-09-22 13:54:07 +0530439 if searchfields:
440 search_columns = ", " + ", ".join(searchfields)
Deepesh Garg1fae7742020-10-05 12:38:54 +0530441 search_cond = " or " + " or ".join([field + " like %(txt)s" for field in searchfields])
Deepesh Garga0d192e2020-09-22 13:54:07 +0530442
Ankush Menat494bd9e2022-03-28 18:52:46 +0530443 if args.get("warehouse"):
444 searchfields = ["batch." + field for field in searchfields]
Deepesh Garga0d192e2020-09-22 13:54:07 +0530445 if searchfields:
446 search_columns = ", " + ", ".join(searchfields)
Deepesh Garg1fae7742020-10-05 12:38:54 +0530447 search_cond = " or " + " or ".join([field + " like %(txt)s" for field in searchfields])
Deepesh Garga0d192e2020-09-22 13:54:07 +0530448
Ankush Menat494bd9e2022-03-28 18:52:46 +0530449 batch_nos = frappe.db.sql(
450 """select sle.batch_no, round(sum(sle.actual_qty),2), sle.stock_uom,
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530451 concat('MFG-',batch.manufacturing_date), concat('EXP-',batch.expiry_date)
Deepesh Garga0d192e2020-09-22 13:54:07 +0530452 {search_columns}
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530453 from `tabStock Ledger Entry` sle
454 INNER JOIN `tabBatch` batch on sle.batch_no = batch.name
455 where
456 batch.disabled = 0
Rohit Waghchaurec14aa452021-07-20 18:19:15 +0530457 and sle.is_cancelled = 0
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530458 and sle.item_code = %(item_code)s
459 and sle.warehouse = %(warehouse)s
460 and (sle.batch_no like %(txt)s
Sun Howwrongbum088be372019-12-24 12:29:25 +0530461 or batch.expiry_date like %(txt)s
Deepesh Gargf58a5ec2020-10-05 13:55:53 +0530462 or batch.manufacturing_date like %(txt)s
463 {search_cond})
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530464 and batch.docstatus < 2
465 {cond}
466 {match_conditions}
467 group by batch_no {having_clause}
468 order by batch.expiry_date, sle.batch_no desc
Conor00ef4992022-06-14 00:19:07 -0500469 limit %(page_len)s offset %(start)s""".format(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530470 search_columns=search_columns,
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530471 cond=cond,
472 match_conditions=get_match_cond(doctype),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530473 having_clause=having_clause,
474 search_cond=search_cond,
475 ),
476 args,
477 )
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530478
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530479 return batch_nos
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530480 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530481 return frappe.db.sql(
482 """select name, concat('MFG-', manufacturing_date), concat('EXP-',expiry_date)
Deepesh Garga0d192e2020-09-22 13:54:07 +0530483 {search_columns}
484 from `tabBatch` batch
Doridel Cahanap59e4c322018-08-06 17:15:18 +0800485 where batch.disabled = 0
486 and item = %(item_code)s
sivankar621740e2018-02-12 14:33:40 +0530487 and (name like %(txt)s
Sun Howwrongbum088be372019-12-24 12:29:25 +0530488 or expiry_date like %(txt)s
Deepesh Gargf58a5ec2020-10-05 13:55:53 +0530489 or manufacturing_date like %(txt)s
490 {search_cond})
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530491 and docstatus < 2
Neil Trini Lasradoebb60f52015-07-08 14:36:09 +0530492 {0}
Anand Doshi0dc79f42015-04-06 12:59:34 +0530493 {match_conditions}
Deepesh Gargf58a5ec2020-10-05 13:55:53 +0530494
Anand Doshi0dc79f42015-04-06 12:59:34 +0530495 order by expiry_date, name desc
Conor00ef4992022-06-14 00:19:07 -0500496 limit %(page_len)s offset %(start)s""".format(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530497 cond,
498 search_columns=search_columns,
499 search_cond=search_cond,
500 match_conditions=get_match_cond(doctype),
501 ),
502 args,
503 )
Nabin Haitea4aa042014-05-28 12:56:28 +0530504
Himanshud94a38e2020-05-18 14:26:26 +0530505
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530506@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530507@frappe.validate_and_sanitize_search_inputs
Nabin Haitea4aa042014-05-28 12:56:28 +0530508def get_account_list(doctype, txt, searchfield, start, page_len, filters):
Sagar Vora9baa2222022-08-03 05:42:30 +0000509 doctype = "Account"
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530510 filter_list = []
Nabin Haitea4aa042014-05-28 12:56:28 +0530511
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530512 if isinstance(filters, dict):
513 for key, val in filters.items():
514 if isinstance(val, (list, tuple)):
515 filter_list.append([doctype, key, val[0], val[1]])
516 else:
517 filter_list.append([doctype, key, "=", val])
bhupeshg2e2e973f2015-04-14 22:15:24 +0530518 elif isinstance(filters, list):
519 filter_list.extend(filters)
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530520
Rushabh Mehta38c6b522015-04-23 13:14:17 +0530521 if "is_group" not in [d[1] for d in filter_list]:
522 filter_list.append(["Account", "is_group", "=", "0"])
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530523
524 if searchfield and txt:
525 filter_list.append([doctype, searchfield, "like", "%%%s%%" % txt])
526
Ankush Menat494bd9e2022-03-28 18:52:46 +0530527 return frappe.desk.reportview.execute(
Sagar Vora9baa2222022-08-03 05:42:30 +0000528 doctype,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530529 filters=filter_list,
530 fields=["name", "parent_account"],
531 limit_start=start,
532 limit_page_length=page_len,
533 as_list=True,
534 )
535
Anand Doshifaefeaa2014-06-24 18:53:04 +0530536
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530537@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530538@frappe.validate_and_sanitize_search_inputs
Marica299e2172020-04-28 13:00:04 +0530539def get_blanket_orders(doctype, txt, searchfield, start, page_len, filters):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530540 return frappe.db.sql(
541 """select distinct bo.name, bo.blanket_order_type, bo.to_date
Marica299e2172020-04-28 13:00:04 +0530542 from `tabBlanket Order` bo, `tabBlanket Order Item` boi
543 where
544 boi.parent = bo.name
545 and boi.item_code = {item_code}
546 and bo.blanket_order_type = '{blanket_order_type}'
547 and bo.company = {company}
Ankush Menat494bd9e2022-03-28 18:52:46 +0530548 and bo.docstatus = 1""".format(
549 item_code=frappe.db.escape(filters.get("item")),
550 blanket_order_type=filters.get("blanket_order_type"),
551 company=frappe.db.escape(filters.get("company")),
552 )
553 )
Nabin Haitafd14f62015-10-19 11:55:28 +0530554
Himanshud94a38e2020-05-18 14:26:26 +0530555
Nabin Haitafd14f62015-10-19 11:55:28 +0530556@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530557@frappe.validate_and_sanitize_search_inputs
Nabin Haitafd14f62015-10-19 11:55:28 +0530558def get_income_account(doctype, txt, searchfield, start, page_len, filters):
559 from erpnext.controllers.queries import get_match_cond
560
561 # income account can be any Credit account,
562 # but can also be a Asset account with account_type='Income Account' in special circumstances.
563 # Hence the first condition is an "OR"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530564 if not filters:
565 filters = {}
Nabin Haitafd14f62015-10-19 11:55:28 +0530566
Sagar Vora9baa2222022-08-03 05:42:30 +0000567 doctype = "Account"
Anand Doshi21e09a22015-10-29 12:21:41 +0530568 condition = ""
Nabin Haitafd14f62015-10-19 11:55:28 +0530569 if filters.get("company"):
570 condition += "and tabAccount.company = %(company)s"
Anand Doshi21e09a22015-10-29 12:21:41 +0530571
Ankush Menat494bd9e2022-03-28 18:52:46 +0530572 return frappe.db.sql(
573 """select tabAccount.name from `tabAccount`
Nabin Haitafd14f62015-10-19 11:55:28 +0530574 where (tabAccount.report_type = "Profit and Loss"
575 or tabAccount.account_type in ("Income Account", "Temporary"))
576 and tabAccount.is_group=0
577 and tabAccount.`{key}` LIKE %(txt)s
Rushabh Mehta3574b372016-03-11 14:33:04 +0530578 {condition} {match_condition}
Ankush Menat494bd9e2022-03-28 18:52:46 +0530579 order by idx desc, name""".format(
580 condition=condition, match_condition=get_match_cond(doctype), key=searchfield
581 ),
582 {"txt": "%" + txt + "%", "company": filters.get("company", "")},
583 )
584
Nabin Hait3a15c922016-03-04 12:30:46 +0530585
Deepesh Garg96e874b2020-11-15 22:43:01 +0530586@frappe.whitelist()
587@frappe.validate_and_sanitize_search_inputs
Ankush Menat6de71eb2023-04-25 18:33:31 +0530588def get_filtered_dimensions(
589 doctype, txt, searchfield, start, page_len, filters, reference_doctype=None
590):
Chillar Anand915b3432021-09-02 16:44:59 +0530591 from erpnext.accounts.doctype.accounting_dimension_filter.accounting_dimension_filter import (
592 get_dimension_filter_map,
593 )
Ankush Menat494bd9e2022-03-28 18:52:46 +0530594
Deepesh Garg96e874b2020-11-15 22:43:01 +0530595 dimension_filters = get_dimension_filter_map()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530596 dimension_filters = dimension_filters.get((filters.get("dimension"), filters.get("account")))
Deepesh Garg6c17b842020-11-25 13:42:16 +0530597 query_filters = []
mergify[bot]071118f2021-11-30 13:15:20 +0000598 or_filters = []
Ankush Menat494bd9e2022-03-28 18:52:46 +0530599 fields = ["name"]
mergify[bot]071118f2021-11-30 13:15:20 +0000600
601 searchfields = frappe.get_meta(doctype).get_search_fields()
Deepesh Garg96e874b2020-11-15 22:43:01 +0530602
603 meta = frappe.get_meta(doctype)
Deepesh Garg96e874b2020-11-15 22:43:01 +0530604 if meta.is_tree:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530605 query_filters.append(["is_group", "=", 0])
Deepesh Garg96e874b2020-11-15 22:43:01 +0530606
Ankush Menat494bd9e2022-03-28 18:52:46 +0530607 if meta.has_field("disabled"):
608 query_filters.append(["disabled", "!=", 1])
Subin Tom333e44e2021-08-18 16:17:54 +0530609
Ankush Menat494bd9e2022-03-28 18:52:46 +0530610 if meta.has_field("company"):
611 query_filters.append(["company", "=", filters.get("company")])
Deepesh Garg6c17b842020-11-25 13:42:16 +0530612
mergify[bot]071118f2021-11-30 13:15:20 +0000613 for field in searchfields:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530614 or_filters.append([field, "LIKE", "%%%s%%" % txt])
mergify[bot]071118f2021-11-30 13:15:20 +0000615 fields.append(field)
Deepesh Garg96e874b2020-11-15 22:43:01 +0530616
617 if dimension_filters:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530618 if dimension_filters["allow_or_restrict"] == "Allow":
619 query_selector = "in"
Deepesh Garg96e874b2020-11-15 22:43:01 +0530620 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530621 query_selector = "not in"
Deepesh Garg96e874b2020-11-15 22:43:01 +0530622
Ankush Menat494bd9e2022-03-28 18:52:46 +0530623 if len(dimension_filters["allowed_dimensions"]) == 1:
624 dimensions = tuple(dimension_filters["allowed_dimensions"] * 2)
Deepesh Garg96e874b2020-11-15 22:43:01 +0530625 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530626 dimensions = tuple(dimension_filters["allowed_dimensions"])
Deepesh Garg96e874b2020-11-15 22:43:01 +0530627
Ankush Menat494bd9e2022-03-28 18:52:46 +0530628 query_filters.append(["name", query_selector, dimensions])
Deepesh Garg96e874b2020-11-15 22:43:01 +0530629
Ankush Menat494bd9e2022-03-28 18:52:46 +0530630 output = frappe.get_list(
Ankush Menat6de71eb2023-04-25 18:33:31 +0530631 doctype,
632 fields=fields,
633 filters=query_filters,
634 or_filters=or_filters,
635 as_list=1,
636 reference_doctype=reference_doctype,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530637 )
Deepesh Garg6c17b842020-11-25 13:42:16 +0530638
mergify[bot]071118f2021-11-30 13:15:20 +0000639 return [tuple(d) for d in set(output)]
Nabin Hait3a15c922016-03-04 12:30:46 +0530640
Ankush Menat494bd9e2022-03-28 18:52:46 +0530641
Nabin Hait3a15c922016-03-04 12:30:46 +0530642@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530643@frappe.validate_and_sanitize_search_inputs
Nabin Hait3a15c922016-03-04 12:30:46 +0530644def get_expense_account(doctype, txt, searchfield, start, page_len, filters):
645 from erpnext.controllers.queries import get_match_cond
Rushabh Mehta203cc962016-04-07 15:25:43 +0530646
Ankush Menat494bd9e2022-03-28 18:52:46 +0530647 if not filters:
648 filters = {}
Nabin Hait3a15c922016-03-04 12:30:46 +0530649
Sagar Vora9baa2222022-08-03 05:42:30 +0000650 doctype = "Account"
Nabin Hait3a15c922016-03-04 12:30:46 +0530651 condition = ""
652 if filters.get("company"):
653 condition += "and tabAccount.company = %(company)s"
Rushabh Mehta203cc962016-04-07 15:25:43 +0530654
Ankush Menat494bd9e2022-03-28 18:52:46 +0530655 return frappe.db.sql(
656 """select tabAccount.name from `tabAccount`
Nabin Hait3a15c922016-03-04 12:30:46 +0530657 where (tabAccount.report_type = "Profit and Loss"
Mangesh-Khairnar5619db22019-08-21 14:49:24 +0530658 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 +0530659 and tabAccount.is_group=0
660 and tabAccount.docstatus!=2
661 and tabAccount.{key} LIKE %(txt)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530662 {condition} {match_condition}""".format(
663 condition=condition, key=searchfield, match_condition=get_match_cond(doctype)
664 ),
665 {"company": filters.get("company", ""), "txt": "%" + txt + "%"},
666 )
suyashphadtare049a88c2017-01-12 17:49:37 +0530667
668
669@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530670@frappe.validate_and_sanitize_search_inputs
suyashphadtare049a88c2017-01-12 17:49:37 +0530671def warehouse_query(doctype, txt, searchfield, start, page_len, filters):
672 # Should be used when item code is passed in filters.
Sagar Vora9baa2222022-08-03 05:42:30 +0000673 doctype = "Warehouse"
suyashphadtare750a0672017-01-18 15:35:01 +0530674 conditions, bin_conditions = [], []
675 filter_dict = get_doctype_wise_filters(filters)
676
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530677 query = """select `tabWarehouse`.name,
Conor74a782d2022-06-17 06:31:27 -0500678 CONCAT_WS(' : ', 'Actual Qty', ifnull(round(`tabBin`.actual_qty, 2), 0 )) actual_qty
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530679 from `tabWarehouse` left join `tabBin`
680 on `tabBin`.warehouse = `tabWarehouse`.name {bin_conditions}
suyashphadtare34ab1362017-01-31 15:14:44 +0530681 where
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530682 `tabWarehouse`.`{key}` like {txt}
suyashphadtare34ab1362017-01-31 15:14:44 +0530683 {fcond} {mcond}
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530684 order by ifnull(`tabBin`.actual_qty, 0) desc
suyashphadtare34ab1362017-01-31 15:14:44 +0530685 limit
Conor00ef4992022-06-14 00:19:07 -0500686 {page_len} offset {start}
suyashphadtare34ab1362017-01-31 15:14:44 +0530687 """.format(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530688 bin_conditions=get_filters_cond(
689 doctype, filter_dict.get("Bin"), bin_conditions, ignore_permissions=True
690 ),
691 key=searchfield,
692 fcond=get_filters_cond(doctype, filter_dict.get("Warehouse"), conditions),
693 mcond=get_match_cond(doctype),
694 start=start,
695 page_len=page_len,
696 txt=frappe.db.escape("%{0}%".format(txt)),
697 )
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530698
699 return frappe.db.sql(query)
suyashphadtare750a0672017-01-18 15:35:01 +0530700
701
702def get_doctype_wise_filters(filters):
703 # Helper function to seperate filters doctype_wise
704 filter_dict = defaultdict(list)
705 for row in filters:
706 filter_dict[row[0]].append(row)
707 return filter_dict
tundebabzy2a4fefc2017-11-29 06:23:09 +0100708
709
710@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530711@frappe.validate_and_sanitize_search_inputs
tundebabzy2a4fefc2017-11-29 06:23:09 +0100712def get_batch_numbers(doctype, txt, searchfield, start, page_len, filters):
rohitwaghchaure9fbed562018-01-12 16:22:33 +0530713 query = """select batch_id from `tabBatch`
Doridel Cahanap59e4c322018-08-06 17:15:18 +0800714 where disabled = 0
Conorb8f728a2022-06-15 01:37:33 -0500715 and (expiry_date >= CURRENT_DATE or expiry_date IS NULL)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530716 and name like {txt}""".format(
717 txt=frappe.db.escape("%{0}%".format(txt))
718 )
tundebabzy2a4fefc2017-11-29 06:23:09 +0100719
Ankush Menat494bd9e2022-03-28 18:52:46 +0530720 if filters and filters.get("item"):
721 query += " and item = {item}".format(item=frappe.db.escape(filters.get("item")))
tundebabzy2a4fefc2017-11-29 06:23:09 +0100722
Sachin Mane64f48db2018-01-08 17:57:32 +0530723 return frappe.db.sql(query, filters)
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530724
Himanshud94a38e2020-05-18 14:26:26 +0530725
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530726@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530727@frappe.validate_and_sanitize_search_inputs
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530728def item_manufacturer_query(doctype, txt, searchfield, start, page_len, filters):
Maricabac4b932019-09-16 19:44:28 +0530729 item_filters = [
Ankush Menat494bd9e2022-03-28 18:52:46 +0530730 ["manufacturer", "like", "%" + txt + "%"],
731 ["item_code", "=", filters.get("item_code")],
Maricabac4b932019-09-16 19:44:28 +0530732 ]
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530733
Maricabac4b932019-09-16 19:44:28 +0530734 item_manufacturers = frappe.get_all(
735 "Item Manufacturer",
736 fields=["manufacturer", "manufacturer_part_no"],
737 filters=item_filters,
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530738 limit_start=start,
739 limit_page_length=page_len,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530740 as_list=1,
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530741 )
Maricabac4b932019-09-16 19:44:28 +0530742 return item_manufacturers
Saqibd9956092019-11-18 11:46:55 +0530743
Himanshud94a38e2020-05-18 14:26:26 +0530744
Saqibd9956092019-11-18 11:46:55 +0530745@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530746@frappe.validate_and_sanitize_search_inputs
Saqibd9956092019-11-18 11:46:55 +0530747def get_purchase_receipts(doctype, txt, searchfield, start, page_len, filters):
748 query = """
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530749 select pr.name
Saqibd9956092019-11-18 11:46:55 +0530750 from `tabPurchase Receipt` pr, `tabPurchase Receipt Item` pritem
751 where pr.docstatus = 1 and pritem.parent = pr.name
Ankush Menat494bd9e2022-03-28 18:52:46 +0530752 and pr.name like {txt}""".format(
753 txt=frappe.db.escape("%{0}%".format(txt))
754 )
Saqibd9956092019-11-18 11:46:55 +0530755
Ankush Menat494bd9e2022-03-28 18:52:46 +0530756 if filters and filters.get("item_code"):
757 query += " and pritem.item_code = {item_code}".format(
758 item_code=frappe.db.escape(filters.get("item_code"))
759 )
Saqibd9956092019-11-18 11:46:55 +0530760
761 return frappe.db.sql(query, filters)
762
Himanshud94a38e2020-05-18 14:26:26 +0530763
Saqibd9956092019-11-18 11:46:55 +0530764@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530765@frappe.validate_and_sanitize_search_inputs
Saqibd9956092019-11-18 11:46:55 +0530766def get_purchase_invoices(doctype, txt, searchfield, start, page_len, filters):
767 query = """
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530768 select pi.name
Saqibd9956092019-11-18 11:46:55 +0530769 from `tabPurchase Invoice` pi, `tabPurchase Invoice Item` piitem
770 where pi.docstatus = 1 and piitem.parent = pi.name
Ankush Menat494bd9e2022-03-28 18:52:46 +0530771 and pi.name like {txt}""".format(
772 txt=frappe.db.escape("%{0}%".format(txt))
773 )
Saqibd9956092019-11-18 11:46:55 +0530774
Ankush Menat494bd9e2022-03-28 18:52:46 +0530775 if filters and filters.get("item_code"):
776 query += " and piitem.item_code = {item_code}".format(
777 item_code=frappe.db.escape(filters.get("item_code"))
778 )
Saqibd9956092019-11-18 11:46:55 +0530779
780 return frappe.db.sql(query, filters)
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530781
Himanshud94a38e2020-05-18 14:26:26 +0530782
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530783@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530784@frappe.validate_and_sanitize_search_inputs
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530785def get_tax_template(doctype, txt, searchfield, start, page_len, filters):
786
Ankush Menat494bd9e2022-03-28 18:52:46 +0530787 item_doc = frappe.get_cached_doc("Item", filters.get("item_code"))
788 item_group = filters.get("item_group")
789 company = filters.get("company")
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530790 taxes = item_doc.taxes or []
791
792 while item_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530793 item_group_doc = frappe.get_cached_doc("Item Group", item_group)
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530794 taxes += item_group_doc.taxes or []
795 item_group = item_group_doc.parent_item_group
796
797 if not taxes:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530798 return frappe.get_all(
799 "Item Tax Template", filters={"disabled": 0, "company": company}, as_list=True
800 )
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530801 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530802 valid_from = filters.get("valid_from")
Marica0fcb05a2020-08-10 14:48:13 +0530803 valid_from = valid_from[1] if isinstance(valid_from, list) else valid_from
804
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530805 args = {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530806 "item_code": filters.get("item_code"),
807 "posting_date": valid_from,
808 "tax_category": filters.get("tax_category"),
809 "company": company,
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530810 }
811
812 taxes = _get_item_tax_template(args, taxes, for_validate=True)
813 return [(d,) for d in set(taxes)]
Himanshud94a38e2020-05-18 14:26:26 +0530814
815
Ankush Menat7eac4a22021-04-19 10:33:39 +0530816def get_fields(doctype, fields=None):
817 if fields is None:
818 fields = []
Himanshud94a38e2020-05-18 14:26:26 +0530819 meta = frappe.get_meta(doctype)
820 fields.extend(meta.get_search_fields())
821
822 if meta.title_field and not meta.title_field.strip() in fields:
823 fields.insert(1, meta.title_field.strip())
824
825 return unique(fields)