blob: 199732b152f70a1498f912d64d582bc0a2caf8c2 [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
ruthra kumar6e3e0942023-11-02 17:19:06 +0530614 condition += f"and tabAccount.disabled = {filters.get('disabled', 0)}"
615
Ankush Menat494bd9e2022-03-28 18:52:46 +0530616 return frappe.db.sql(
617 """select tabAccount.name from `tabAccount`
Nabin Haitafd14f62015-10-19 11:55:28 +0530618 where (tabAccount.report_type = "Profit and Loss"
619 or tabAccount.account_type in ("Income Account", "Temporary"))
620 and tabAccount.is_group=0
621 and tabAccount.`{key}` LIKE %(txt)s
Rushabh Mehta3574b372016-03-11 14:33:04 +0530622 {condition} {match_condition}
Ankush Menat494bd9e2022-03-28 18:52:46 +0530623 order by idx desc, name""".format(
624 condition=condition, match_condition=get_match_cond(doctype), key=searchfield
625 ),
626 {"txt": "%" + txt + "%", "company": filters.get("company", "")},
627 )
628
Nabin Hait3a15c922016-03-04 12:30:46 +0530629
Deepesh Garg96e874b2020-11-15 22:43:01 +0530630@frappe.whitelist()
631@frappe.validate_and_sanitize_search_inputs
Ankush Menat6de71eb2023-04-25 18:33:31 +0530632def get_filtered_dimensions(
633 doctype, txt, searchfield, start, page_len, filters, reference_doctype=None
634):
Chillar Anand915b3432021-09-02 16:44:59 +0530635 from erpnext.accounts.doctype.accounting_dimension_filter.accounting_dimension_filter import (
636 get_dimension_filter_map,
637 )
Ankush Menat494bd9e2022-03-28 18:52:46 +0530638
Deepesh Garg96e874b2020-11-15 22:43:01 +0530639 dimension_filters = get_dimension_filter_map()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530640 dimension_filters = dimension_filters.get((filters.get("dimension"), filters.get("account")))
Deepesh Garg6c17b842020-11-25 13:42:16 +0530641 query_filters = []
mergify[bot]071118f2021-11-30 13:15:20 +0000642 or_filters = []
Ankush Menat494bd9e2022-03-28 18:52:46 +0530643 fields = ["name"]
mergify[bot]071118f2021-11-30 13:15:20 +0000644
645 searchfields = frappe.get_meta(doctype).get_search_fields()
Deepesh Garg96e874b2020-11-15 22:43:01 +0530646
647 meta = frappe.get_meta(doctype)
Deepesh Garg96e874b2020-11-15 22:43:01 +0530648 if meta.is_tree:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530649 query_filters.append(["is_group", "=", 0])
Deepesh Garg96e874b2020-11-15 22:43:01 +0530650
Ankush Menat494bd9e2022-03-28 18:52:46 +0530651 if meta.has_field("disabled"):
652 query_filters.append(["disabled", "!=", 1])
Subin Tom333e44e2021-08-18 16:17:54 +0530653
Ankush Menat494bd9e2022-03-28 18:52:46 +0530654 if meta.has_field("company"):
655 query_filters.append(["company", "=", filters.get("company")])
Deepesh Garg6c17b842020-11-25 13:42:16 +0530656
mergify[bot]071118f2021-11-30 13:15:20 +0000657 for field in searchfields:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530658 or_filters.append([field, "LIKE", "%%%s%%" % txt])
mergify[bot]071118f2021-11-30 13:15:20 +0000659 fields.append(field)
Deepesh Garg96e874b2020-11-15 22:43:01 +0530660
661 if dimension_filters:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530662 if dimension_filters["allow_or_restrict"] == "Allow":
663 query_selector = "in"
Deepesh Garg96e874b2020-11-15 22:43:01 +0530664 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530665 query_selector = "not in"
Deepesh Garg96e874b2020-11-15 22:43:01 +0530666
Ankush Menat494bd9e2022-03-28 18:52:46 +0530667 if len(dimension_filters["allowed_dimensions"]) == 1:
668 dimensions = tuple(dimension_filters["allowed_dimensions"] * 2)
Deepesh Garg96e874b2020-11-15 22:43:01 +0530669 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530670 dimensions = tuple(dimension_filters["allowed_dimensions"])
Deepesh Garg96e874b2020-11-15 22:43:01 +0530671
Ankush Menat494bd9e2022-03-28 18:52:46 +0530672 query_filters.append(["name", query_selector, dimensions])
Deepesh Garg96e874b2020-11-15 22:43:01 +0530673
Ankush Menat494bd9e2022-03-28 18:52:46 +0530674 output = frappe.get_list(
Ankush Menat6de71eb2023-04-25 18:33:31 +0530675 doctype,
676 fields=fields,
677 filters=query_filters,
678 or_filters=or_filters,
679 as_list=1,
680 reference_doctype=reference_doctype,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530681 )
Deepesh Garg6c17b842020-11-25 13:42:16 +0530682
mergify[bot]071118f2021-11-30 13:15:20 +0000683 return [tuple(d) for d in set(output)]
Nabin Hait3a15c922016-03-04 12:30:46 +0530684
Ankush Menat494bd9e2022-03-28 18:52:46 +0530685
Nabin Hait3a15c922016-03-04 12:30:46 +0530686@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530687@frappe.validate_and_sanitize_search_inputs
Nabin Hait3a15c922016-03-04 12:30:46 +0530688def get_expense_account(doctype, txt, searchfield, start, page_len, filters):
689 from erpnext.controllers.queries import get_match_cond
Rushabh Mehta203cc962016-04-07 15:25:43 +0530690
Ankush Menat494bd9e2022-03-28 18:52:46 +0530691 if not filters:
692 filters = {}
Nabin Hait3a15c922016-03-04 12:30:46 +0530693
Sagar Vora9baa2222022-08-03 05:42:30 +0000694 doctype = "Account"
Nabin Hait3a15c922016-03-04 12:30:46 +0530695 condition = ""
696 if filters.get("company"):
697 condition += "and tabAccount.company = %(company)s"
Rushabh Mehta203cc962016-04-07 15:25:43 +0530698
Ankush Menat494bd9e2022-03-28 18:52:46 +0530699 return frappe.db.sql(
700 """select tabAccount.name from `tabAccount`
Nabin Hait3a15c922016-03-04 12:30:46 +0530701 where (tabAccount.report_type = "Profit and Loss"
Mangesh-Khairnar5619db22019-08-21 14:49:24 +0530702 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 +0530703 and tabAccount.is_group=0
704 and tabAccount.docstatus!=2
705 and tabAccount.{key} LIKE %(txt)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530706 {condition} {match_condition}""".format(
707 condition=condition, key=searchfield, match_condition=get_match_cond(doctype)
708 ),
709 {"company": filters.get("company", ""), "txt": "%" + txt + "%"},
710 )
suyashphadtare049a88c2017-01-12 17:49:37 +0530711
712
713@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530714@frappe.validate_and_sanitize_search_inputs
suyashphadtare049a88c2017-01-12 17:49:37 +0530715def warehouse_query(doctype, txt, searchfield, start, page_len, filters):
716 # Should be used when item code is passed in filters.
Sagar Vora9baa2222022-08-03 05:42:30 +0000717 doctype = "Warehouse"
suyashphadtare750a0672017-01-18 15:35:01 +0530718 conditions, bin_conditions = [], []
719 filter_dict = get_doctype_wise_filters(filters)
720
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530721 query = """select `tabWarehouse`.name,
Conor74a782d2022-06-17 06:31:27 -0500722 CONCAT_WS(' : ', 'Actual Qty', ifnull(round(`tabBin`.actual_qty, 2), 0 )) actual_qty
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530723 from `tabWarehouse` left join `tabBin`
724 on `tabBin`.warehouse = `tabWarehouse`.name {bin_conditions}
suyashphadtare34ab1362017-01-31 15:14:44 +0530725 where
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530726 `tabWarehouse`.`{key}` like {txt}
suyashphadtare34ab1362017-01-31 15:14:44 +0530727 {fcond} {mcond}
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530728 order by ifnull(`tabBin`.actual_qty, 0) desc
suyashphadtare34ab1362017-01-31 15:14:44 +0530729 limit
Conor00ef4992022-06-14 00:19:07 -0500730 {page_len} offset {start}
suyashphadtare34ab1362017-01-31 15:14:44 +0530731 """.format(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530732 bin_conditions=get_filters_cond(
733 doctype, filter_dict.get("Bin"), bin_conditions, ignore_permissions=True
734 ),
735 key=searchfield,
736 fcond=get_filters_cond(doctype, filter_dict.get("Warehouse"), conditions),
737 mcond=get_match_cond(doctype),
738 start=start,
739 page_len=page_len,
740 txt=frappe.db.escape("%{0}%".format(txt)),
741 )
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530742
743 return frappe.db.sql(query)
suyashphadtare750a0672017-01-18 15:35:01 +0530744
745
746def get_doctype_wise_filters(filters):
747 # Helper function to seperate filters doctype_wise
748 filter_dict = defaultdict(list)
749 for row in filters:
750 filter_dict[row[0]].append(row)
751 return filter_dict
tundebabzy2a4fefc2017-11-29 06:23:09 +0100752
753
754@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530755@frappe.validate_and_sanitize_search_inputs
tundebabzy2a4fefc2017-11-29 06:23:09 +0100756def get_batch_numbers(doctype, txt, searchfield, start, page_len, filters):
rohitwaghchaure9fbed562018-01-12 16:22:33 +0530757 query = """select batch_id from `tabBatch`
Doridel Cahanap59e4c322018-08-06 17:15:18 +0800758 where disabled = 0
Conorb8f728a2022-06-15 01:37:33 -0500759 and (expiry_date >= CURRENT_DATE or expiry_date IS NULL)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530760 and name like {txt}""".format(
761 txt=frappe.db.escape("%{0}%".format(txt))
762 )
tundebabzy2a4fefc2017-11-29 06:23:09 +0100763
Ankush Menat494bd9e2022-03-28 18:52:46 +0530764 if filters and filters.get("item"):
765 query += " and item = {item}".format(item=frappe.db.escape(filters.get("item")))
tundebabzy2a4fefc2017-11-29 06:23:09 +0100766
Sachin Mane64f48db2018-01-08 17:57:32 +0530767 return frappe.db.sql(query, filters)
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530768
Himanshud94a38e2020-05-18 14:26:26 +0530769
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530770@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530771@frappe.validate_and_sanitize_search_inputs
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530772def item_manufacturer_query(doctype, txt, searchfield, start, page_len, filters):
Maricabac4b932019-09-16 19:44:28 +0530773 item_filters = [
Ankush Menat494bd9e2022-03-28 18:52:46 +0530774 ["manufacturer", "like", "%" + txt + "%"],
775 ["item_code", "=", filters.get("item_code")],
Maricabac4b932019-09-16 19:44:28 +0530776 ]
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530777
Maricabac4b932019-09-16 19:44:28 +0530778 item_manufacturers = frappe.get_all(
779 "Item Manufacturer",
780 fields=["manufacturer", "manufacturer_part_no"],
781 filters=item_filters,
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530782 limit_start=start,
783 limit_page_length=page_len,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530784 as_list=1,
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530785 )
Maricabac4b932019-09-16 19:44:28 +0530786 return item_manufacturers
Saqibd9956092019-11-18 11:46:55 +0530787
Himanshud94a38e2020-05-18 14:26:26 +0530788
Saqibd9956092019-11-18 11:46:55 +0530789@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530790@frappe.validate_and_sanitize_search_inputs
Saqibd9956092019-11-18 11:46:55 +0530791def get_purchase_receipts(doctype, txt, searchfield, start, page_len, filters):
792 query = """
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530793 select pr.name
Saqibd9956092019-11-18 11:46:55 +0530794 from `tabPurchase Receipt` pr, `tabPurchase Receipt Item` pritem
795 where pr.docstatus = 1 and pritem.parent = pr.name
Ankush Menat494bd9e2022-03-28 18:52:46 +0530796 and pr.name like {txt}""".format(
797 txt=frappe.db.escape("%{0}%".format(txt))
798 )
Saqibd9956092019-11-18 11:46:55 +0530799
Ankush Menat494bd9e2022-03-28 18:52:46 +0530800 if filters and filters.get("item_code"):
801 query += " and pritem.item_code = {item_code}".format(
802 item_code=frappe.db.escape(filters.get("item_code"))
803 )
Saqibd9956092019-11-18 11:46:55 +0530804
805 return frappe.db.sql(query, filters)
806
Himanshud94a38e2020-05-18 14:26:26 +0530807
Saqibd9956092019-11-18 11:46:55 +0530808@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530809@frappe.validate_and_sanitize_search_inputs
Saqibd9956092019-11-18 11:46:55 +0530810def get_purchase_invoices(doctype, txt, searchfield, start, page_len, filters):
811 query = """
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530812 select pi.name
Saqibd9956092019-11-18 11:46:55 +0530813 from `tabPurchase Invoice` pi, `tabPurchase Invoice Item` piitem
814 where pi.docstatus = 1 and piitem.parent = pi.name
Ankush Menat494bd9e2022-03-28 18:52:46 +0530815 and pi.name like {txt}""".format(
816 txt=frappe.db.escape("%{0}%".format(txt))
817 )
Saqibd9956092019-11-18 11:46:55 +0530818
Ankush Menat494bd9e2022-03-28 18:52:46 +0530819 if filters and filters.get("item_code"):
820 query += " and piitem.item_code = {item_code}".format(
821 item_code=frappe.db.escape(filters.get("item_code"))
822 )
Saqibd9956092019-11-18 11:46:55 +0530823
824 return frappe.db.sql(query, filters)
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530825
Himanshud94a38e2020-05-18 14:26:26 +0530826
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530827@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530828@frappe.validate_and_sanitize_search_inputs
mergify[bot]b4db5e92023-07-18 17:40:49 +0530829def get_doctypes_for_closing(doctype, txt, searchfield, start, page_len, filters):
830 doctypes = frappe.get_hooks("period_closing_doctypes")
831 if txt:
832 doctypes = [d for d in doctypes if txt.lower() in d.lower()]
833 return [(d,) for d in set(doctypes)]
834
835
836@frappe.whitelist()
837@frappe.validate_and_sanitize_search_inputs
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530838def get_tax_template(doctype, txt, searchfield, start, page_len, filters):
839
Ankush Menat494bd9e2022-03-28 18:52:46 +0530840 item_doc = frappe.get_cached_doc("Item", filters.get("item_code"))
841 item_group = filters.get("item_group")
842 company = filters.get("company")
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530843 taxes = item_doc.taxes or []
844
845 while item_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530846 item_group_doc = frappe.get_cached_doc("Item Group", item_group)
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530847 taxes += item_group_doc.taxes or []
848 item_group = item_group_doc.parent_item_group
849
850 if not taxes:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530851 return frappe.get_all(
852 "Item Tax Template", filters={"disabled": 0, "company": company}, as_list=True
853 )
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530854 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530855 valid_from = filters.get("valid_from")
Marica0fcb05a2020-08-10 14:48:13 +0530856 valid_from = valid_from[1] if isinstance(valid_from, list) else valid_from
857
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530858 args = {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530859 "item_code": filters.get("item_code"),
860 "posting_date": valid_from,
861 "tax_category": filters.get("tax_category"),
862 "company": company,
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530863 }
864
865 taxes = _get_item_tax_template(args, taxes, for_validate=True)
866 return [(d,) for d in set(taxes)]
Himanshud94a38e2020-05-18 14:26:26 +0530867
868
Ankush Menat7eac4a22021-04-19 10:33:39 +0530869def get_fields(doctype, fields=None):
870 if fields is None:
871 fields = []
Himanshud94a38e2020-05-18 14:26:26 +0530872 meta = frappe.get_meta(doctype)
873 fields.extend(meta.get_search_fields())
874
875 if meta.title_field and not meta.title_field.strip() in fields:
876 fields.insert(1, meta.title_field.strip())
877
878 return unique(fields)
ruthra kumar662ccd42023-07-22 11:18:11 +0530879
880
881@frappe.whitelist()
882@frappe.validate_and_sanitize_search_inputs
883def get_payment_terms_for_references(doctype, txt, searchfield, start, page_len, filters) -> list:
884 terms = []
885 if filters:
886 terms = frappe.db.get_all(
887 "Payment Schedule",
888 filters={"parent": filters.get("reference")},
889 fields=["payment_term"],
890 limit=page_len,
891 as_list=1,
892 )
893 return terms