blob: 3bb11282f1f8732cbdcbd23f84027d1d06ce9983 [file] [log] [blame]
Anand Doshi885e0742015-03-03 14:55:30 +05301# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
Rushabh Mehtae67d1fb2013-08-05 14:59:54 +05302# License: GNU General Public License v3. See license.txt
Saurabh02875592013-07-08 18:45:55 +05303
Chillar Anand915b3432021-09-02 16:44:59 +05304
rohitwaghchaurec59371a2021-06-03 20:02:58 +05305import json
Rohit Waghchaureacd12c52023-06-04 16:09:01 +05306from collections import OrderedDict, defaultdict
Chillar Anand915b3432021-09-02 16:44:59 +05307
8import frappe
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
Rohit Waghchaureacd12c52023-06-04 16:09:01 +053011from frappe.query_builder.functions import Concat, Sum
12from frappe.utils import nowdate, today, unique
Chillar Anand915b3432021-09-02 16:44:59 +053013
14import erpnext
Deepesh Gargef0d26c2020-01-06 15:34:15 +053015from erpnext.stock.get_item_details import _get_item_tax_template
Chillar Anand915b3432021-09-02 16:44:59 +053016
Saurabh02875592013-07-08 18:45:55 +053017
Chinmay D. Paiaa121092020-07-01 21:14:32 +053018# searches for active employees
19@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +053020@frappe.validate_and_sanitize_search_inputs
Saurabh02875592013-07-08 18:45:55 +053021def employee_query(doctype, txt, searchfield, start, page_len, filters):
Sagar Vora9baa2222022-08-03 05:42:30 +000022 doctype = "Employee"
Kanchan Chauhan7652b852016-11-16 15:29:01 +053023 conditions = []
Sagar Vora9baa2222022-08-03 05:42:30 +000024 fields = get_fields(doctype, ["name", "employee_name"])
Himanshud94a38e2020-05-18 14:26:26 +053025
Ankush Menat494bd9e2022-03-28 18:52:46 +053026 return frappe.db.sql(
27 """select {fields} from `tabEmployee`
Anurag Mishrafc98abe2021-06-23 11:21:38 +053028 where status in ('Active', 'Suspended')
Anand Doshibd67e872014-04-11 16:51:27 +053029 and docstatus < 2
Anand Doshi48d3b542014-07-09 13:15:03 +053030 and ({key} like %(txt)s
31 or employee_name like %(txt)s)
Kanchan Chauhan7652b852016-11-16 15:29:01 +053032 {fcond} {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +053033 order by
Conorea28ed12022-06-17 10:47:48 -050034 (case when locate(%(_txt)s, name) > 0 then locate(%(_txt)s, name) else 99999 end),
35 (case when locate(%(_txt)s, employee_name) > 0 then locate(%(_txt)s, employee_name) else 99999 end),
Rushabh Mehta3574b372016-03-11 14:33:04 +053036 idx desc,
Anand Doshi652bc072014-04-16 15:21:46 +053037 name, employee_name
Conor00ef4992022-06-14 00:19:07 -050038 limit %(page_len)s offset %(start)s""".format(
Ankush Menat494bd9e2022-03-28 18:52:46 +053039 **{
40 "fields": ", ".join(fields),
41 "key": searchfield,
42 "fcond": get_filters_cond(doctype, filters, conditions),
43 "mcond": get_match_cond(doctype),
44 }
45 ),
46 {"txt": "%%%s%%" % txt, "_txt": txt.replace("%", ""), "start": start, "page_len": page_len},
47 )
Saurabh02875592013-07-08 18:45:55 +053048
Himanshud94a38e2020-05-18 14:26:26 +053049
50# searches for leads which are not converted
Chinmay D. Paiaa121092020-07-01 21:14:32 +053051@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +053052@frappe.validate_and_sanitize_search_inputs
Anand Doshibd67e872014-04-11 16:51:27 +053053def lead_query(doctype, txt, searchfield, start, page_len, filters):
Sagar Vora9baa2222022-08-03 05:42:30 +000054 doctype = "Lead"
55 fields = get_fields(doctype, ["name", "lead_name", "company_name"])
Himanshud94a38e2020-05-18 14:26:26 +053056
HarryPauloe12e3bb2023-05-13 23:38:47 -030057 searchfields = frappe.get_meta(doctype).get_search_fields()
58 searchfields = " or ".join(field + " like %(txt)s" for field in searchfields)
59
Ankush Menat494bd9e2022-03-28 18:52:46 +053060 return frappe.db.sql(
61 """select {fields} from `tabLead`
Anand Doshibd67e872014-04-11 16:51:27 +053062 where docstatus < 2
63 and ifnull(status, '') != 'Converted'
Anand Doshi48d3b542014-07-09 13:15:03 +053064 and ({key} like %(txt)s
65 or lead_name like %(txt)s
HarryPauloe12e3bb2023-05-13 23:38:47 -030066 or company_name like %(txt)s
67 or {scond})
Anand Doshi48d3b542014-07-09 13:15:03 +053068 {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +053069 order by
Conorea28ed12022-06-17 10:47:48 -050070 (case when locate(%(_txt)s, name) > 0 then locate(%(_txt)s, name) else 99999 end),
71 (case when locate(%(_txt)s, lead_name) > 0 then locate(%(_txt)s, lead_name) else 99999 end),
72 (case when locate(%(_txt)s, company_name) > 0 then locate(%(_txt)s, company_name) else 99999 end),
Rushabh Mehta3574b372016-03-11 14:33:04 +053073 idx desc,
Anand Doshi652bc072014-04-16 15:21:46 +053074 name, lead_name
Conor00ef4992022-06-14 00:19:07 -050075 limit %(page_len)s offset %(start)s""".format(
HarryPauloe12e3bb2023-05-13 23:38:47 -030076 **{
77 "fields": ", ".join(fields),
78 "key": searchfield,
79 "scond": searchfields,
80 "mcond": get_match_cond(doctype),
81 }
Ankush Menat494bd9e2022-03-28 18:52:46 +053082 ),
83 {"txt": "%%%s%%" % txt, "_txt": txt.replace("%", ""), "start": start, "page_len": page_len},
84 )
85
86 # searches for customer
Saurabh02875592013-07-08 18:45:55 +053087
Himanshud94a38e2020-05-18 14:26:26 +053088
Chinmay D. Paiaa121092020-07-01 21:14:32 +053089@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +053090@frappe.validate_and_sanitize_search_inputs
Rohit Waghchaure5f849932022-10-24 16:10:47 +053091def customer_query(doctype, txt, searchfield, start, page_len, filters, as_dict=False):
Sagar Vora9baa2222022-08-03 05:42:30 +000092 doctype = "Customer"
KanchanChauhan4b888b92017-07-25 14:03:01 +053093 conditions = []
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053094 cust_master_name = frappe.defaults.get_user_default("cust_master_name")
Saurabhf52dc072013-07-10 13:07:49 +053095
Rohit Waghchaure46d148d2022-10-24 15:48:34 +053096 fields = ["name"]
97 if cust_master_name != "Customer Name":
Rohit Waghchaureb0fc5682022-11-03 11:24:58 +053098 fields.append("customer_name")
Rushabh Mehtab92087c2017-01-13 18:53:11 +053099
Sagar Vora9baa2222022-08-03 05:42:30 +0000100 fields = get_fields(doctype, fields)
Sagar Vora9baa2222022-08-03 05:42:30 +0000101 searchfields = frappe.get_meta(doctype).get_search_fields()
Ankush Menata9c84f72021-06-11 16:00:48 +0530102 searchfields = " or ".join(field + " like %(txt)s" for field in searchfields)
Saurabh02875592013-07-08 18:45:55 +0530103
Ankush Menat494bd9e2022-03-28 18:52:46 +0530104 return frappe.db.sql(
105 """select {fields} from `tabCustomer`
Anand Doshibd67e872014-04-11 16:51:27 +0530106 where docstatus < 2
Console Admin86231662017-06-23 20:32:52 +0300107 and ({scond}) and disabled=0
KanchanChauhan4b888b92017-07-25 14:03:01 +0530108 {fcond} {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +0530109 order by
Conorea28ed12022-06-17 10:47:48 -0500110 (case when locate(%(_txt)s, name) > 0 then locate(%(_txt)s, name) else 99999 end),
111 (case when locate(%(_txt)s, customer_name) > 0 then locate(%(_txt)s, customer_name) else 99999 end),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530112 idx desc,
Anand Doshibd67e872014-04-11 16:51:27 +0530113 name, customer_name
Conor00ef4992022-06-14 00:19:07 -0500114 limit %(page_len)s offset %(start)s""".format(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530115 **{
116 "fields": ", ".join(fields),
117 "scond": searchfields,
118 "mcond": get_match_cond(doctype),
119 "fcond": get_filters_cond(doctype, filters, conditions).replace("%", "%%"),
120 }
121 ),
122 {"txt": "%%%s%%" % txt, "_txt": txt.replace("%", ""), "start": start, "page_len": page_len},
Rohit Waghchaure5f849932022-10-24 16:10:47 +0530123 as_dict=as_dict,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530124 )
Saurabh02875592013-07-08 18:45:55 +0530125
Himanshud94a38e2020-05-18 14:26:26 +0530126
Saurabh02875592013-07-08 18:45:55 +0530127# searches for supplier
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530128@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530129@frappe.validate_and_sanitize_search_inputs
Rohit Waghchaure5f849932022-10-24 16:10:47 +0530130def supplier_query(doctype, txt, searchfield, start, page_len, filters, as_dict=False):
Sagar Vora9baa2222022-08-03 05:42:30 +0000131 doctype = "Supplier"
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530132 supp_master_name = frappe.defaults.get_user_default("supp_master_name")
Suraj Shetty1923ef02020-08-05 19:42:25 +0530133
Rohit Waghchaure46d148d2022-10-24 15:48:34 +0530134 fields = ["name"]
135 if supp_master_name != "Supplier Name":
Rohit Waghchaureb0fc5682022-11-03 11:24:58 +0530136 fields.append("supplier_name")
Himanshud94a38e2020-05-18 14:26:26 +0530137
Sagar Vora9baa2222022-08-03 05:42:30 +0000138 fields = get_fields(doctype, fields)
Saurabh02875592013-07-08 18:45:55 +0530139
Ankush Menat494bd9e2022-03-28 18:52:46 +0530140 return frappe.db.sql(
141 """select {field} from `tabSupplier`
Anand Doshibd67e872014-04-11 16:51:27 +0530142 where docstatus < 2
Anand Doshi48d3b542014-07-09 13:15:03 +0530143 and ({key} like %(txt)s
Ankush Menat2221c9e2021-10-27 19:15:44 +0530144 or supplier_name like %(txt)s) and disabled=0
Conorea28ed12022-06-17 10:47:48 -0500145 and (on_hold = 0 or (on_hold = 1 and CURRENT_DATE > release_date))
Anand Doshi48d3b542014-07-09 13:15:03 +0530146 {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +0530147 order by
Conorea28ed12022-06-17 10:47:48 -0500148 (case when locate(%(_txt)s, name) > 0 then locate(%(_txt)s, name) else 99999 end),
149 (case when locate(%(_txt)s, supplier_name) > 0 then locate(%(_txt)s, supplier_name) else 99999 end),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530150 idx desc,
Anand Doshibd67e872014-04-11 16:51:27 +0530151 name, supplier_name
Conor00ef4992022-06-14 00:19:07 -0500152 limit %(page_len)s offset %(start)s""".format(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530153 **{"field": ", ".join(fields), "key": searchfield, "mcond": get_match_cond(doctype)}
154 ),
155 {"txt": "%%%s%%" % txt, "_txt": txt.replace("%", ""), "start": start, "page_len": page_len},
Rohit Waghchaure5f849932022-10-24 16:10:47 +0530156 as_dict=as_dict,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530157 )
Anand Doshibd67e872014-04-11 16:51:27 +0530158
Himanshud94a38e2020-05-18 14:26:26 +0530159
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530160@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530161@frappe.validate_and_sanitize_search_inputs
Nabin Hait9a380ef2013-07-16 17:24:17 +0530162def tax_account_query(doctype, txt, searchfield, start, page_len, filters):
Sagar Vora9baa2222022-08-03 05:42:30 +0000163 doctype = "Account"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530164 company_currency = erpnext.get_company_currency(filters.get("company"))
Deepesh Gargfbf6e562020-03-31 10:45:32 +0530165
Suraj Shetty1923ef02020-08-05 19:42:25 +0530166 def get_accounts(with_account_type_filter):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530167 account_type_condition = ""
Suraj Shetty1923ef02020-08-05 19:42:25 +0530168 if with_account_type_filter:
169 account_type_condition = "AND account_type in %(account_types)s"
170
Ankush Menat494bd9e2022-03-28 18:52:46 +0530171 accounts = frappe.db.sql(
172 """
Suraj Shetty1923ef02020-08-05 19:42:25 +0530173 SELECT name, parent_account
174 FROM `tabAccount`
175 WHERE `tabAccount`.docstatus!=2
176 {account_type_condition}
177 AND is_group = 0
178 AND company = %(company)s
Saqib Ansaria1e3ae82022-05-11 13:01:06 +0530179 AND disabled = %(disabled)s
Deepesh Garg57924592022-03-22 18:26:58 +0530180 AND (account_currency = %(currency)s or ifnull(account_currency, '') = '')
Suraj Shetty1923ef02020-08-05 19:42:25 +0530181 AND `{searchfield}` LIKE %(txt)s
prssannade7a2bc2020-09-21 13:57:04 +0530182 {mcond}
Suraj Shetty1923ef02020-08-05 19:42:25 +0530183 ORDER BY idx DESC, name
Conor00ef4992022-06-14 00:19:07 -0500184 LIMIT %(limit)s offset %(offset)s
prssannade7a2bc2020-09-21 13:57:04 +0530185 """.format(
186 account_type_condition=account_type_condition,
187 searchfield=searchfield,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530188 mcond=get_match_cond(doctype),
prssannade7a2bc2020-09-21 13:57:04 +0530189 ),
Suraj Shetty1923ef02020-08-05 19:42:25 +0530190 dict(
191 account_types=filters.get("account_type"),
192 company=filters.get("company"),
Saqib Ansaria1e3ae82022-05-11 13:01:06 +0530193 disabled=filters.get("disabled", 0),
Suraj Shetty1923ef02020-08-05 19:42:25 +0530194 currency=company_currency,
195 txt="%{}%".format(txt),
196 offset=start,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530197 limit=page_len,
198 ),
Suraj Shetty1923ef02020-08-05 19:42:25 +0530199 )
200
201 return accounts
202
203 tax_accounts = get_accounts(True)
204
Nabin Hait0c21e2a2014-03-21 11:14:49 +0530205 if not tax_accounts:
Suraj Shetty1923ef02020-08-05 19:42:25 +0530206 tax_accounts = get_accounts(False)
Anand Doshibd67e872014-04-11 16:51:27 +0530207
Nabin Hait0c21e2a2014-03-21 11:14:49 +0530208 return tax_accounts
Saurabh02875592013-07-08 18:45:55 +0530209
Himanshud94a38e2020-05-18 14:26:26 +0530210
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530211@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530212@frappe.validate_and_sanitize_search_inputs
Rushabh Mehta203cc962016-04-07 15:25:43 +0530213def item_query(doctype, txt, searchfield, start, page_len, filters, as_dict=False):
Sagar Vora9baa2222022-08-03 05:42:30 +0000214 doctype = "Item"
Saurabh02875592013-07-08 18:45:55 +0530215 conditions = []
Saurabhf52dc072013-07-10 13:07:49 +0530216
rohitwaghchaurec59371a2021-06-03 20:02:58 +0530217 if isinstance(filters, str):
218 filters = json.loads(filters)
219
Ankush Menat494bd9e2022-03-28 18:52:46 +0530220 # Get searchfields from meta and use in Item Link field query
Sagar Vora9baa2222022-08-03 05:42:30 +0000221 meta = frappe.get_meta(doctype, cached=True)
marination3dbef9d2019-10-28 15:48:10 +0530222 searchfields = meta.get_search_fields()
223
Ankush Menat494bd9e2022-03-28 18:52:46 +0530224 columns = ""
Rohit Waghchaurefd889fd2022-09-28 23:00:45 +0530225 extra_searchfields = [field for field in searchfields if not field in ["name", "description"]]
Rohit Waghchaurec42312e2019-11-19 19:05:23 +0530226
227 if extra_searchfields:
Rohit Waghchaurefd889fd2022-09-28 23:00:45 +0530228 columns += ", " + ", ".join(extra_searchfields)
229
230 if "description" in searchfields:
231 columns += """, if(length(tabItem.description) > 40, \
232 concat(substr(tabItem.description, 1, 40), "..."), description) as description"""
marination1e754b12019-10-30 18:33:44 +0530233
Ankush Menat494bd9e2022-03-28 18:52:46 +0530234 searchfields = searchfields + [
235 field
236 for field in [searchfield or "name", "item_code", "item_group", "item_name"]
237 if not field in searchfields
238 ]
marination3dbef9d2019-10-28 15:48:10 +0530239 searchfields = " or ".join([field + " like %(txt)s" for field in searchfields])
240
DeeMysterioaa826242021-09-14 13:58:18 +0530241 if filters and isinstance(filters, dict):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530242 if filters.get("customer") or filters.get("supplier"):
243 party = filters.get("customer") or filters.get("supplier")
244 item_rules_list = frappe.get_all(
245 "Party Specific Item", filters={"party": party}, fields=["restrict_based_on", "based_on_value"]
246 )
Rohit Waghchaure721b4132021-06-02 14:13:09 +0530247
DeeMysterioaa826242021-09-14 13:58:18 +0530248 filters_dict = {}
249 for rule in item_rules_list:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530250 if rule["restrict_based_on"] == "Item":
251 rule["restrict_based_on"] = "name"
DeeMysterioaa826242021-09-14 13:58:18 +0530252 filters_dict[rule.restrict_based_on] = []
noahjacobca2fb472021-05-12 16:25:07 +0530253
DeeMysterioaa826242021-09-14 13:58:18 +0530254 for rule in item_rules_list:
255 filters_dict[rule.restrict_based_on].append(rule.based_on_value)
noahjacobca2fb472021-05-12 16:25:07 +0530256
DeeMysterioaa826242021-09-14 13:58:18 +0530257 for filter in filters_dict:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530258 filters[scrub(filter)] = ["in", filters_dict[filter]]
DeeMysterioaa826242021-09-14 13:58:18 +0530259
Ankush Menat494bd9e2022-03-28 18:52:46 +0530260 if filters.get("customer"):
261 del filters["customer"]
DeeMysterioaa826242021-09-14 13:58:18 +0530262 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530263 del filters["supplier"]
Ankush Menat41a95e52022-02-03 13:02:13 +0530264 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530265 filters.pop("customer", None)
266 filters.pop("supplier", None)
DeeMysterioaa826242021-09-14 13:58:18 +0530267
Ankush Menat494bd9e2022-03-28 18:52:46 +0530268 description_cond = ""
Sagar Vora9baa2222022-08-03 05:42:30 +0000269 if frappe.db.count(doctype, cache=True) < 50000:
Rushabh Mehtad5f9ebd2018-04-02 23:37:33 +0530270 # scan description only if items are less than 50000
Ankush Menat494bd9e2022-03-28 18:52:46 +0530271 description_cond = "or tabItem.description LIKE %(txt)s"
Rohit Waghchaurefd889fd2022-09-28 23:00:45 +0530272
Ankush Menat494bd9e2022-03-28 18:52:46 +0530273 return frappe.db.sql(
274 """select
Rohit Waghchaurefd889fd2022-09-28 23:00:45 +0530275 tabItem.name {columns}
Anand Doshibd67e872014-04-11 16:51:27 +0530276 from tabItem
Anand Doshi22c0d782013-11-04 16:23:04 +0530277 where tabItem.docstatus < 2
Anand Doshi21e09a22015-10-29 12:21:41 +0530278 and tabItem.disabled=0
rohitwaghchaure79789072020-05-21 18:10:13 +0530279 and tabItem.has_variants=0
Rushabh Mehta864d1ea2014-06-23 12:20:12 +0530280 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 +0530281 and ({scond} or tabItem.item_code IN (select parent from `tabItem Barcode` where barcode LIKE %(txt)s)
Rohit Waghchaure2bfb0632019-03-02 21:47:55 +0530282 {description_cond})
Anand Doshi22c0d782013-11-04 16:23:04 +0530283 {fcond} {mcond}
Anand Doshi652bc072014-04-16 15:21:46 +0530284 order by
285 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
286 if(locate(%(_txt)s, item_name), locate(%(_txt)s, item_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530287 idx desc,
Anand Doshi652bc072014-04-16 15:21:46 +0530288 name, item_name
Rushabh Mehtabc4e2cd2017-10-17 12:30:34 +0530289 limit %(start)s, %(page_len)s """.format(
marination1e754b12019-10-30 18:33:44 +0530290 columns=columns,
marination3dbef9d2019-10-28 15:48:10 +0530291 scond=searchfields,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530292 fcond=get_filters_cond(doctype, filters, conditions).replace("%", "%%"),
293 mcond=get_match_cond(doctype).replace("%", "%%"),
294 description_cond=description_cond,
295 ),
296 {
297 "today": nowdate(),
298 "txt": "%%%s%%" % txt,
299 "_txt": txt.replace("%", ""),
300 "start": start,
301 "page_len": page_len,
302 },
303 as_dict=as_dict,
304 )
Saurabh02875592013-07-08 18:45:55 +0530305
Himanshud94a38e2020-05-18 14:26:26 +0530306
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530307@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530308@frappe.validate_and_sanitize_search_inputs
Saurabh022ab632017-11-10 15:06:02 +0530309def bom(doctype, txt, searchfield, start, page_len, filters):
Sagar Vora9baa2222022-08-03 05:42:30 +0000310 doctype = "BOM"
Anand Doshibd67e872014-04-11 16:51:27 +0530311 conditions = []
Sagar Vora9baa2222022-08-03 05:42:30 +0000312 fields = get_fields(doctype, ["name", "item"])
Saurabhf52dc072013-07-10 13:07:49 +0530313
Ankush Menat494bd9e2022-03-28 18:52:46 +0530314 return frappe.db.sql(
315 """select {fields}
Conorea28ed12022-06-17 10:47:48 -0500316 from `tabBOM`
317 where `tabBOM`.docstatus=1
318 and `tabBOM`.is_active=1
319 and `tabBOM`.`{key}` like %(txt)s
Nabin Hait62211172016-03-16 16:22:03 +0530320 {fcond} {mcond}
321 order by
Conorea28ed12022-06-17 10:47:48 -0500322 (case when locate(%(_txt)s, name) > 0 then locate(%(_txt)s, name) else 99999 end),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530323 idx desc, name
Conorea28ed12022-06-17 10:47:48 -0500324 limit %(page_len)s offset %(start)s""".format(
Himanshud94a38e2020-05-18 14:26:26 +0530325 fields=", ".join(fields),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530326 fcond=get_filters_cond(doctype, filters, conditions).replace("%", "%%"),
327 mcond=get_match_cond(doctype).replace("%", "%%"),
328 key=searchfield,
329 ),
Mangesh-Khairnar6a796912019-07-08 10:40:40 +0530330 {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530331 "txt": "%" + txt + "%",
332 "_txt": txt.replace("%", ""),
333 "start": start or 0,
334 "page_len": page_len or 20,
335 },
336 )
Saurabh02875592013-07-08 18:45:55 +0530337
Himanshud94a38e2020-05-18 14:26:26 +0530338
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530339@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530340@frappe.validate_and_sanitize_search_inputs
Saurabh02875592013-07-08 18:45:55 +0530341def get_project_name(doctype, txt, searchfield, start, page_len, filters):
Sagar Vora9baa2222022-08-03 05:42:30 +0000342 doctype = "Project"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530343 cond = ""
344 if filters and filters.get("customer"):
Suraj Shetty6ea3de92018-09-26 18:15:53 +0530345 cond = """(`tabProject`.customer = %s or
Ankush Menat494bd9e2022-03-28 18:52:46 +0530346 ifnull(`tabProject`.customer,"")="") and""" % (
347 frappe.db.escape(filters.get("customer"))
348 )
Anand Doshibd67e872014-04-11 16:51:27 +0530349
Sagar Vora9baa2222022-08-03 05:42:30 +0000350 fields = get_fields(doctype, ["name", "project_name"])
351 searchfields = frappe.get_meta(doctype).get_search_fields()
Conor74a782d2022-06-17 06:31:27 -0500352 searchfields = " or ".join(["`tabProject`." + field + " like %(txt)s" for field in searchfields])
Himanshud94a38e2020-05-18 14:26:26 +0530353
Ankush Menat494bd9e2022-03-28 18:52:46 +0530354 return frappe.db.sql(
355 """select {fields} from `tabProject`
Rucha Mahabal062d3012021-05-07 13:31:14 +0530356 where
Conor74a782d2022-06-17 06:31:27 -0500357 `tabProject`.status not in ('Completed', 'Cancelled')
Subin Tom889140f2021-06-22 16:26:19 +0530358 and {cond} {scond} {match_cond}
Rushabh Mehta3574b372016-03-11 14:33:04 +0530359 order by
Conorea28ed12022-06-17 10:47:48 -0500360 (case when locate(%(_txt)s, `tabProject`.name) > 0 then locate(%(_txt)s, `tabProject`.name) else 99999 end),
361 `tabProject`.idx desc,
Rushabh Mehta3574b372016-03-11 14:33:04 +0530362 `tabProject`.name asc
Conor00ef4992022-06-14 00:19:07 -0500363 limit {page_len} offset {start}""".format(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530364 fields=", ".join(["`tabProject`.{0}".format(f) for f in fields]),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530365 cond=cond,
Rucha Mahabal062d3012021-05-07 13:31:14 +0530366 scond=searchfields,
Rushabh Mehta3574b372016-03-11 14:33:04 +0530367 match_cond=get_match_cond(doctype),
368 start=start,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530369 page_len=page_len,
370 ),
371 {"txt": "%{0}%".format(txt), "_txt": txt.replace("%", "")},
372 )
Anand Doshibd67e872014-04-11 16:51:27 +0530373
tundebabzyf6d738b2017-09-18 12:40:09 +0100374
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530375@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530376@frappe.validate_and_sanitize_search_inputs
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530377def get_delivery_notes_to_be_billed(doctype, txt, searchfield, start, page_len, filters, as_dict):
Sagar Vora9baa2222022-08-03 05:42:30 +0000378 doctype = "Delivery Note"
379 fields = get_fields(doctype, ["name", "customer", "posting_date"])
Himanshud94a38e2020-05-18 14:26:26 +0530380
Ankush Menat494bd9e2022-03-28 18:52:46 +0530381 return frappe.db.sql(
382 """
Himanshud94a38e2020-05-18 14:26:26 +0530383 select %(fields)s
Anand Doshibd67e872014-04-11 16:51:27 +0530384 from `tabDelivery Note`
385 where `tabDelivery Note`.`%(key)s` like %(txt)s and
tundebabzyf6d738b2017-09-18 12:40:09 +0100386 `tabDelivery Note`.docstatus = 1
Conor74a782d2022-06-17 06:31:27 -0500387 and status not in ('Stopped', 'Closed') %(fcond)s
tundebabzyf6d738b2017-09-18 12:40:09 +0100388 and (
389 (`tabDelivery Note`.is_return = 0 and `tabDelivery Note`.per_billed < 100)
Deepesh Garge2dc1022021-04-14 11:21:11 +0530390 or (`tabDelivery Note`.grand_total = 0 and `tabDelivery Note`.per_billed < 100)
tundebabzyf6d738b2017-09-18 12:40:09 +0100391 or (
392 `tabDelivery Note`.is_return = 1
393 and return_against in (select name from `tabDelivery Note` where per_billed < 100)
394 )
395 )
Conor00ef4992022-06-14 00:19:07 -0500396 %(mcond)s order by `tabDelivery Note`.`%(key)s` asc limit %(page_len)s offset %(start)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530397 """
398 % {
399 "fields": ", ".join(["`tabDelivery Note`.{0}".format(f) for f in fields]),
400 "key": searchfield,
401 "fcond": get_filters_cond(doctype, filters, []),
402 "mcond": get_match_cond(doctype),
403 "start": start,
404 "page_len": page_len,
405 "txt": "%(txt)s",
406 },
407 {"txt": ("%%%s%%" % txt)},
408 as_dict=as_dict,
409 )
tundebabzyf6d738b2017-09-18 12:40:09 +0100410
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530411
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530412@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530413@frappe.validate_and_sanitize_search_inputs
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530414def get_batch_no(doctype, txt, searchfield, start, page_len, filters):
Sagar Vora9baa2222022-08-03 05:42:30 +0000415 doctype = "Batch"
Sagar Vora9baa2222022-08-03 05:42:30 +0000416 meta = frappe.get_meta(doctype, cached=True)
Deepesh Garga0d192e2020-09-22 13:54:07 +0530417 searchfields = meta.get_search_fields()
418
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530419 query = get_batches_from_stock_ledger_entries(searchfields, txt, filters)
420 bundle_query = get_batches_from_serial_and_batch_bundle(searchfields, txt, filters)
Deepesh Gargf58a5ec2020-10-05 13:55:53 +0530421
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530422 data = (
423 frappe.qb.from_((query) + (bundle_query))
424 .select("batch_no", "qty", "manufacturing_date", "expiry_date")
425 .offset(start)
426 .limit(page_len)
427 )
Deepesh Garga0d192e2020-09-22 13:54:07 +0530428
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530429 for field in searchfields:
430 data = data.select(field)
Deepesh Garga0d192e2020-09-22 13:54:07 +0530431
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530432 data = data.run()
433 data = get_filterd_batches(data)
434
435 return data
436
437
438def get_filterd_batches(data):
439 batches = OrderedDict()
440
441 for batch_data in data:
442 if batch_data[0] not in batches:
443 batches[batch_data[0]] = list(batch_data)
444 else:
445 batches[batch_data[0]][1] += batch_data[1]
446
447 filterd_batch = []
448 for batch, batch_data in batches.items():
449 if batch_data[1] > 0:
450 filterd_batch.append(tuple(batch_data))
451
452 return filterd_batch
453
454
455def get_batches_from_stock_ledger_entries(searchfields, txt, filters):
456 stock_ledger_entry = frappe.qb.DocType("Stock Ledger Entry")
457 batch_table = frappe.qb.DocType("Batch")
458
459 expiry_date = filters.get("posting_date") or today()
460
461 query = (
462 frappe.qb.from_(stock_ledger_entry)
463 .inner_join(batch_table)
464 .on(batch_table.name == stock_ledger_entry.batch_no)
465 .select(
466 stock_ledger_entry.batch_no,
467 Sum(stock_ledger_entry.actual_qty).as_("qty"),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530468 )
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530469 .where(((batch_table.expiry_date >= expiry_date) | (batch_table.expiry_date.isnull())))
470 .where(stock_ledger_entry.is_cancelled == 0)
471 .where(
472 (stock_ledger_entry.item_code == filters.get("item_code"))
473 & (batch_table.disabled == 0)
474 & (stock_ledger_entry.batch_no.isnotnull())
Ankush Menat494bd9e2022-03-28 18:52:46 +0530475 )
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530476 .groupby(stock_ledger_entry.batch_no, stock_ledger_entry.warehouse)
477 )
478
479 query = query.select(
480 Concat("MFG-", batch_table.manufacturing_date).as_("manufacturing_date"),
481 Concat("EXP-", batch_table.expiry_date).as_("expiry_date"),
482 )
483
484 if filters.get("warehouse"):
485 query = query.where(stock_ledger_entry.warehouse == filters.get("warehouse"))
486
487 for field in searchfields:
488 query = query.select(batch_table[field])
489
490 if txt:
491 txt_condition = batch_table.name.like(txt)
492 for field in searchfields + ["name"]:
493 txt_condition |= batch_table[field].like(txt)
494
495 query = query.where(txt_condition)
496
497 return query
498
499
500def get_batches_from_serial_and_batch_bundle(searchfields, txt, filters):
501 bundle = frappe.qb.DocType("Serial and Batch Entry")
502 stock_ledger_entry = frappe.qb.DocType("Stock Ledger Entry")
503 batch_table = frappe.qb.DocType("Batch")
504
505 expiry_date = filters.get("posting_date") or today()
506
507 bundle_query = (
508 frappe.qb.from_(bundle)
509 .inner_join(stock_ledger_entry)
510 .on(bundle.parent == stock_ledger_entry.serial_and_batch_bundle)
511 .inner_join(batch_table)
512 .on(batch_table.name == bundle.batch_no)
513 .select(
514 bundle.batch_no,
515 Sum(bundle.qty).as_("qty"),
516 )
517 .where(((batch_table.expiry_date >= expiry_date) | (batch_table.expiry_date.isnull())))
518 .where(stock_ledger_entry.is_cancelled == 0)
519 .where(
520 (stock_ledger_entry.item_code == filters.get("item_code"))
521 & (batch_table.disabled == 0)
522 & (stock_ledger_entry.serial_and_batch_bundle.isnotnull())
523 )
524 .groupby(bundle.batch_no, bundle.warehouse)
525 )
526
527 bundle_query = bundle_query.select(
528 Concat("MFG-", batch_table.manufacturing_date),
529 Concat("EXP-", batch_table.expiry_date),
530 )
531
532 if filters.get("warehouse"):
533 bundle_query = bundle_query.where(stock_ledger_entry.warehouse == filters.get("warehouse"))
534
535 for field in searchfields:
536 bundle_query = bundle_query.select(batch_table[field])
537
538 if txt:
539 txt_condition = batch_table.name.like(txt)
540 for field in searchfields + ["name"]:
541 txt_condition |= batch_table[field].like(txt)
542
543 bundle_query = bundle_query.where(txt_condition)
544
545 return bundle_query
Nabin Haitea4aa042014-05-28 12:56:28 +0530546
Himanshud94a38e2020-05-18 14:26:26 +0530547
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530548@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530549@frappe.validate_and_sanitize_search_inputs
Nabin Haitea4aa042014-05-28 12:56:28 +0530550def get_account_list(doctype, txt, searchfield, start, page_len, filters):
Sagar Vora9baa2222022-08-03 05:42:30 +0000551 doctype = "Account"
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530552 filter_list = []
Nabin Haitea4aa042014-05-28 12:56:28 +0530553
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530554 if isinstance(filters, dict):
555 for key, val in filters.items():
556 if isinstance(val, (list, tuple)):
557 filter_list.append([doctype, key, val[0], val[1]])
558 else:
559 filter_list.append([doctype, key, "=", val])
bhupeshg2e2e973f2015-04-14 22:15:24 +0530560 elif isinstance(filters, list):
561 filter_list.extend(filters)
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530562
Rushabh Mehta38c6b522015-04-23 13:14:17 +0530563 if "is_group" not in [d[1] for d in filter_list]:
564 filter_list.append(["Account", "is_group", "=", "0"])
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530565
566 if searchfield and txt:
567 filter_list.append([doctype, searchfield, "like", "%%%s%%" % txt])
568
Ankush Menat494bd9e2022-03-28 18:52:46 +0530569 return frappe.desk.reportview.execute(
Sagar Vora9baa2222022-08-03 05:42:30 +0000570 doctype,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530571 filters=filter_list,
572 fields=["name", "parent_account"],
573 limit_start=start,
574 limit_page_length=page_len,
575 as_list=True,
576 )
577
Anand Doshifaefeaa2014-06-24 18:53:04 +0530578
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530579@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530580@frappe.validate_and_sanitize_search_inputs
Marica299e2172020-04-28 13:00:04 +0530581def get_blanket_orders(doctype, txt, searchfield, start, page_len, filters):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530582 return frappe.db.sql(
583 """select distinct bo.name, bo.blanket_order_type, bo.to_date
Marica299e2172020-04-28 13:00:04 +0530584 from `tabBlanket Order` bo, `tabBlanket Order Item` boi
585 where
586 boi.parent = bo.name
587 and boi.item_code = {item_code}
588 and bo.blanket_order_type = '{blanket_order_type}'
589 and bo.company = {company}
Ankush Menat494bd9e2022-03-28 18:52:46 +0530590 and bo.docstatus = 1""".format(
591 item_code=frappe.db.escape(filters.get("item")),
592 blanket_order_type=filters.get("blanket_order_type"),
593 company=frappe.db.escape(filters.get("company")),
594 )
595 )
Nabin Haitafd14f62015-10-19 11:55:28 +0530596
Himanshud94a38e2020-05-18 14:26:26 +0530597
Nabin Haitafd14f62015-10-19 11:55:28 +0530598@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530599@frappe.validate_and_sanitize_search_inputs
Nabin Haitafd14f62015-10-19 11:55:28 +0530600def get_income_account(doctype, txt, searchfield, start, page_len, filters):
601 from erpnext.controllers.queries import get_match_cond
602
603 # income account can be any Credit account,
604 # but can also be a Asset account with account_type='Income Account' in special circumstances.
605 # Hence the first condition is an "OR"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530606 if not filters:
607 filters = {}
Nabin Haitafd14f62015-10-19 11:55:28 +0530608
Sagar Vora9baa2222022-08-03 05:42:30 +0000609 doctype = "Account"
Anand Doshi21e09a22015-10-29 12:21:41 +0530610 condition = ""
Nabin Haitafd14f62015-10-19 11:55:28 +0530611 if filters.get("company"):
612 condition += "and tabAccount.company = %(company)s"
Anand Doshi21e09a22015-10-29 12:21:41 +0530613
Ankush Menat494bd9e2022-03-28 18:52:46 +0530614 return frappe.db.sql(
615 """select tabAccount.name from `tabAccount`
Nabin Haitafd14f62015-10-19 11:55:28 +0530616 where (tabAccount.report_type = "Profit and Loss"
617 or tabAccount.account_type in ("Income Account", "Temporary"))
618 and tabAccount.is_group=0
619 and tabAccount.`{key}` LIKE %(txt)s
Rushabh Mehta3574b372016-03-11 14:33:04 +0530620 {condition} {match_condition}
Ankush Menat494bd9e2022-03-28 18:52:46 +0530621 order by idx desc, name""".format(
622 condition=condition, match_condition=get_match_cond(doctype), key=searchfield
623 ),
624 {"txt": "%" + txt + "%", "company": filters.get("company", "")},
625 )
626
Nabin Hait3a15c922016-03-04 12:30:46 +0530627
Deepesh Garg96e874b2020-11-15 22:43:01 +0530628@frappe.whitelist()
629@frappe.validate_and_sanitize_search_inputs
Ankush Menat6de71eb2023-04-25 18:33:31 +0530630def get_filtered_dimensions(
631 doctype, txt, searchfield, start, page_len, filters, reference_doctype=None
632):
Chillar Anand915b3432021-09-02 16:44:59 +0530633 from erpnext.accounts.doctype.accounting_dimension_filter.accounting_dimension_filter import (
634 get_dimension_filter_map,
635 )
Ankush Menat494bd9e2022-03-28 18:52:46 +0530636
Deepesh Garg96e874b2020-11-15 22:43:01 +0530637 dimension_filters = get_dimension_filter_map()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530638 dimension_filters = dimension_filters.get((filters.get("dimension"), filters.get("account")))
Deepesh Garg6c17b842020-11-25 13:42:16 +0530639 query_filters = []
mergify[bot]071118f2021-11-30 13:15:20 +0000640 or_filters = []
Ankush Menat494bd9e2022-03-28 18:52:46 +0530641 fields = ["name"]
mergify[bot]071118f2021-11-30 13:15:20 +0000642
643 searchfields = frappe.get_meta(doctype).get_search_fields()
Deepesh Garg96e874b2020-11-15 22:43:01 +0530644
645 meta = frappe.get_meta(doctype)
Deepesh Garg96e874b2020-11-15 22:43:01 +0530646 if meta.is_tree:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530647 query_filters.append(["is_group", "=", 0])
Deepesh Garg96e874b2020-11-15 22:43:01 +0530648
Ankush Menat494bd9e2022-03-28 18:52:46 +0530649 if meta.has_field("disabled"):
650 query_filters.append(["disabled", "!=", 1])
Subin Tom333e44e2021-08-18 16:17:54 +0530651
Ankush Menat494bd9e2022-03-28 18:52:46 +0530652 if meta.has_field("company"):
653 query_filters.append(["company", "=", filters.get("company")])
Deepesh Garg6c17b842020-11-25 13:42:16 +0530654
mergify[bot]071118f2021-11-30 13:15:20 +0000655 for field in searchfields:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530656 or_filters.append([field, "LIKE", "%%%s%%" % txt])
mergify[bot]071118f2021-11-30 13:15:20 +0000657 fields.append(field)
Deepesh Garg96e874b2020-11-15 22:43:01 +0530658
659 if dimension_filters:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530660 if dimension_filters["allow_or_restrict"] == "Allow":
661 query_selector = "in"
Deepesh Garg96e874b2020-11-15 22:43:01 +0530662 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530663 query_selector = "not in"
Deepesh Garg96e874b2020-11-15 22:43:01 +0530664
Ankush Menat494bd9e2022-03-28 18:52:46 +0530665 if len(dimension_filters["allowed_dimensions"]) == 1:
666 dimensions = tuple(dimension_filters["allowed_dimensions"] * 2)
Deepesh Garg96e874b2020-11-15 22:43:01 +0530667 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530668 dimensions = tuple(dimension_filters["allowed_dimensions"])
Deepesh Garg96e874b2020-11-15 22:43:01 +0530669
Ankush Menat494bd9e2022-03-28 18:52:46 +0530670 query_filters.append(["name", query_selector, dimensions])
Deepesh Garg96e874b2020-11-15 22:43:01 +0530671
Ankush Menat494bd9e2022-03-28 18:52:46 +0530672 output = frappe.get_list(
Ankush Menat6de71eb2023-04-25 18:33:31 +0530673 doctype,
674 fields=fields,
675 filters=query_filters,
676 or_filters=or_filters,
677 as_list=1,
678 reference_doctype=reference_doctype,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530679 )
Deepesh Garg6c17b842020-11-25 13:42:16 +0530680
mergify[bot]071118f2021-11-30 13:15:20 +0000681 return [tuple(d) for d in set(output)]
Nabin Hait3a15c922016-03-04 12:30:46 +0530682
Ankush Menat494bd9e2022-03-28 18:52:46 +0530683
Nabin Hait3a15c922016-03-04 12:30:46 +0530684@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530685@frappe.validate_and_sanitize_search_inputs
Nabin Hait3a15c922016-03-04 12:30:46 +0530686def get_expense_account(doctype, txt, searchfield, start, page_len, filters):
687 from erpnext.controllers.queries import get_match_cond
Rushabh Mehta203cc962016-04-07 15:25:43 +0530688
Ankush Menat494bd9e2022-03-28 18:52:46 +0530689 if not filters:
690 filters = {}
Nabin Hait3a15c922016-03-04 12:30:46 +0530691
Sagar Vora9baa2222022-08-03 05:42:30 +0000692 doctype = "Account"
Nabin Hait3a15c922016-03-04 12:30:46 +0530693 condition = ""
694 if filters.get("company"):
695 condition += "and tabAccount.company = %(company)s"
Rushabh Mehta203cc962016-04-07 15:25:43 +0530696
Ankush Menat494bd9e2022-03-28 18:52:46 +0530697 return frappe.db.sql(
698 """select tabAccount.name from `tabAccount`
Nabin Hait3a15c922016-03-04 12:30:46 +0530699 where (tabAccount.report_type = "Profit and Loss"
Mangesh-Khairnar5619db22019-08-21 14:49:24 +0530700 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 +0530701 and tabAccount.is_group=0
702 and tabAccount.docstatus!=2
703 and tabAccount.{key} LIKE %(txt)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530704 {condition} {match_condition}""".format(
705 condition=condition, key=searchfield, match_condition=get_match_cond(doctype)
706 ),
707 {"company": filters.get("company", ""), "txt": "%" + txt + "%"},
708 )
suyashphadtare049a88c2017-01-12 17:49:37 +0530709
710
711@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530712@frappe.validate_and_sanitize_search_inputs
suyashphadtare049a88c2017-01-12 17:49:37 +0530713def warehouse_query(doctype, txt, searchfield, start, page_len, filters):
714 # Should be used when item code is passed in filters.
Sagar Vora9baa2222022-08-03 05:42:30 +0000715 doctype = "Warehouse"
suyashphadtare750a0672017-01-18 15:35:01 +0530716 conditions, bin_conditions = [], []
717 filter_dict = get_doctype_wise_filters(filters)
718
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530719 query = """select `tabWarehouse`.name,
Conor74a782d2022-06-17 06:31:27 -0500720 CONCAT_WS(' : ', 'Actual Qty', ifnull(round(`tabBin`.actual_qty, 2), 0 )) actual_qty
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530721 from `tabWarehouse` left join `tabBin`
722 on `tabBin`.warehouse = `tabWarehouse`.name {bin_conditions}
suyashphadtare34ab1362017-01-31 15:14:44 +0530723 where
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530724 `tabWarehouse`.`{key}` like {txt}
suyashphadtare34ab1362017-01-31 15:14:44 +0530725 {fcond} {mcond}
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530726 order by ifnull(`tabBin`.actual_qty, 0) desc
suyashphadtare34ab1362017-01-31 15:14:44 +0530727 limit
Conor00ef4992022-06-14 00:19:07 -0500728 {page_len} offset {start}
suyashphadtare34ab1362017-01-31 15:14:44 +0530729 """.format(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530730 bin_conditions=get_filters_cond(
731 doctype, filter_dict.get("Bin"), bin_conditions, ignore_permissions=True
732 ),
733 key=searchfield,
734 fcond=get_filters_cond(doctype, filter_dict.get("Warehouse"), conditions),
735 mcond=get_match_cond(doctype),
736 start=start,
737 page_len=page_len,
738 txt=frappe.db.escape("%{0}%".format(txt)),
739 )
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530740
741 return frappe.db.sql(query)
suyashphadtare750a0672017-01-18 15:35:01 +0530742
743
744def get_doctype_wise_filters(filters):
745 # Helper function to seperate filters doctype_wise
746 filter_dict = defaultdict(list)
747 for row in filters:
748 filter_dict[row[0]].append(row)
749 return filter_dict
tundebabzy2a4fefc2017-11-29 06:23:09 +0100750
751
752@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530753@frappe.validate_and_sanitize_search_inputs
tundebabzy2a4fefc2017-11-29 06:23:09 +0100754def get_batch_numbers(doctype, txt, searchfield, start, page_len, filters):
rohitwaghchaure9fbed562018-01-12 16:22:33 +0530755 query = """select batch_id from `tabBatch`
Doridel Cahanap59e4c322018-08-06 17:15:18 +0800756 where disabled = 0
Conorb8f728a2022-06-15 01:37:33 -0500757 and (expiry_date >= CURRENT_DATE or expiry_date IS NULL)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530758 and name like {txt}""".format(
759 txt=frappe.db.escape("%{0}%".format(txt))
760 )
tundebabzy2a4fefc2017-11-29 06:23:09 +0100761
Ankush Menat494bd9e2022-03-28 18:52:46 +0530762 if filters and filters.get("item"):
763 query += " and item = {item}".format(item=frappe.db.escape(filters.get("item")))
tundebabzy2a4fefc2017-11-29 06:23:09 +0100764
Sachin Mane64f48db2018-01-08 17:57:32 +0530765 return frappe.db.sql(query, filters)
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530766
Himanshud94a38e2020-05-18 14:26:26 +0530767
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530768@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530769@frappe.validate_and_sanitize_search_inputs
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530770def item_manufacturer_query(doctype, txt, searchfield, start, page_len, filters):
Maricabac4b932019-09-16 19:44:28 +0530771 item_filters = [
Ankush Menat494bd9e2022-03-28 18:52:46 +0530772 ["manufacturer", "like", "%" + txt + "%"],
773 ["item_code", "=", filters.get("item_code")],
Maricabac4b932019-09-16 19:44:28 +0530774 ]
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530775
Maricabac4b932019-09-16 19:44:28 +0530776 item_manufacturers = frappe.get_all(
777 "Item Manufacturer",
778 fields=["manufacturer", "manufacturer_part_no"],
779 filters=item_filters,
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530780 limit_start=start,
781 limit_page_length=page_len,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530782 as_list=1,
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530783 )
Maricabac4b932019-09-16 19:44:28 +0530784 return item_manufacturers
Saqibd9956092019-11-18 11:46:55 +0530785
Himanshud94a38e2020-05-18 14:26:26 +0530786
Saqibd9956092019-11-18 11:46:55 +0530787@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530788@frappe.validate_and_sanitize_search_inputs
Saqibd9956092019-11-18 11:46:55 +0530789def get_purchase_receipts(doctype, txt, searchfield, start, page_len, filters):
790 query = """
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530791 select pr.name
Saqibd9956092019-11-18 11:46:55 +0530792 from `tabPurchase Receipt` pr, `tabPurchase Receipt Item` pritem
793 where pr.docstatus = 1 and pritem.parent = pr.name
Ankush Menat494bd9e2022-03-28 18:52:46 +0530794 and pr.name like {txt}""".format(
795 txt=frappe.db.escape("%{0}%".format(txt))
796 )
Saqibd9956092019-11-18 11:46:55 +0530797
Ankush Menat494bd9e2022-03-28 18:52:46 +0530798 if filters and filters.get("item_code"):
799 query += " and pritem.item_code = {item_code}".format(
800 item_code=frappe.db.escape(filters.get("item_code"))
801 )
Saqibd9956092019-11-18 11:46:55 +0530802
803 return frappe.db.sql(query, filters)
804
Himanshud94a38e2020-05-18 14:26:26 +0530805
Saqibd9956092019-11-18 11:46:55 +0530806@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530807@frappe.validate_and_sanitize_search_inputs
Saqibd9956092019-11-18 11:46:55 +0530808def get_purchase_invoices(doctype, txt, searchfield, start, page_len, filters):
809 query = """
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530810 select pi.name
Saqibd9956092019-11-18 11:46:55 +0530811 from `tabPurchase Invoice` pi, `tabPurchase Invoice Item` piitem
812 where pi.docstatus = 1 and piitem.parent = pi.name
Ankush Menat494bd9e2022-03-28 18:52:46 +0530813 and pi.name like {txt}""".format(
814 txt=frappe.db.escape("%{0}%".format(txt))
815 )
Saqibd9956092019-11-18 11:46:55 +0530816
Ankush Menat494bd9e2022-03-28 18:52:46 +0530817 if filters and filters.get("item_code"):
818 query += " and piitem.item_code = {item_code}".format(
819 item_code=frappe.db.escape(filters.get("item_code"))
820 )
Saqibd9956092019-11-18 11:46:55 +0530821
822 return frappe.db.sql(query, filters)
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530823
Himanshud94a38e2020-05-18 14:26:26 +0530824
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530825@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530826@frappe.validate_and_sanitize_search_inputs
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530827def get_tax_template(doctype, txt, searchfield, start, page_len, filters):
828
Ankush Menat494bd9e2022-03-28 18:52:46 +0530829 item_doc = frappe.get_cached_doc("Item", filters.get("item_code"))
830 item_group = filters.get("item_group")
831 company = filters.get("company")
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530832 taxes = item_doc.taxes or []
833
834 while item_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530835 item_group_doc = frappe.get_cached_doc("Item Group", item_group)
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530836 taxes += item_group_doc.taxes or []
837 item_group = item_group_doc.parent_item_group
838
839 if not taxes:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530840 return frappe.get_all(
841 "Item Tax Template", filters={"disabled": 0, "company": company}, as_list=True
842 )
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530843 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530844 valid_from = filters.get("valid_from")
Marica0fcb05a2020-08-10 14:48:13 +0530845 valid_from = valid_from[1] if isinstance(valid_from, list) else valid_from
846
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530847 args = {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530848 "item_code": filters.get("item_code"),
849 "posting_date": valid_from,
850 "tax_category": filters.get("tax_category"),
851 "company": company,
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530852 }
853
854 taxes = _get_item_tax_template(args, taxes, for_validate=True)
855 return [(d,) for d in set(taxes)]
Himanshud94a38e2020-05-18 14:26:26 +0530856
857
Ankush Menat7eac4a22021-04-19 10:33:39 +0530858def get_fields(doctype, fields=None):
859 if fields is None:
860 fields = []
Himanshud94a38e2020-05-18 14:26:26 +0530861 meta = frappe.get_meta(doctype)
862 fields.extend(meta.get_search_fields())
863
864 if meta.title_field and not meta.title_field.strip() in fields:
865 fields.insert(1, meta.title_field.strip())
866
867 return unique(fields)