blob: 21c052a39127bf3a214e5807964d8da48bd73771 [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
4from __future__ import unicode_literals
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05305import frappe
Deepesh Gargfbf6e562020-03-31 10:45:32 +05306import erpnext
rohitwaghchaurec59371a2021-06-03 20:02:58 +05307import json
Rushabh Mehtab92087c2017-01-13 18:53:11 +05308from frappe.desk.reportview import get_match_cond, get_filters_cond
Deepesh Gargef0d26c2020-01-06 15:34:15 +05309from frappe.utils import nowdate, getdate
suyashphadtare750a0672017-01-18 15:35:01 +053010from collections import defaultdict
Deepesh Gargef0d26c2020-01-06 15:34:15 +053011from erpnext.stock.get_item_details import _get_item_tax_template
Himanshud94a38e2020-05-18 14:26:26 +053012from frappe.utils import unique
Saurabh02875592013-07-08 18:45:55 +053013
Chinmay D. Paiaa121092020-07-01 21:14:32 +053014# searches for active employees
15@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +053016@frappe.validate_and_sanitize_search_inputs
Saurabh02875592013-07-08 18:45:55 +053017def employee_query(doctype, txt, searchfield, start, page_len, filters):
Kanchan Chauhan7652b852016-11-16 15:29:01 +053018 conditions = []
Himanshud94a38e2020-05-18 14:26:26 +053019 fields = get_fields("Employee", ["name", "employee_name"])
20
21 return frappe.db.sql("""select {fields} from `tabEmployee`
Anurag Mishrafc98abe2021-06-23 11:21:38 +053022 where status in ('Active', 'Suspended')
Anand Doshibd67e872014-04-11 16:51:27 +053023 and docstatus < 2
Anand Doshi48d3b542014-07-09 13:15:03 +053024 and ({key} like %(txt)s
25 or employee_name like %(txt)s)
Kanchan Chauhan7652b852016-11-16 15:29:01 +053026 {fcond} {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +053027 order by
Anand Doshi48d3b542014-07-09 13:15:03 +053028 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
29 if(locate(%(_txt)s, employee_name), locate(%(_txt)s, employee_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +053030 idx desc,
Anand Doshi652bc072014-04-16 15:21:46 +053031 name, employee_name
Anand Doshi48d3b542014-07-09 13:15:03 +053032 limit %(start)s, %(page_len)s""".format(**{
Himanshud94a38e2020-05-18 14:26:26 +053033 'fields': ", ".join(fields),
Anand Doshi48d3b542014-07-09 13:15:03 +053034 'key': searchfield,
Kanchan Chauhan7652b852016-11-16 15:29:01 +053035 'fcond': get_filters_cond(doctype, filters, conditions),
Anand Doshi48d3b542014-07-09 13:15:03 +053036 'mcond': get_match_cond(doctype)
37 }), {
38 'txt': "%%%s%%" % txt,
39 '_txt': txt.replace("%", ""),
40 'start': start,
41 'page_len': page_len
42 })
Saurabh02875592013-07-08 18:45:55 +053043
Himanshud94a38e2020-05-18 14:26:26 +053044
45# searches for leads which are not converted
Chinmay D. Paiaa121092020-07-01 21:14:32 +053046@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +053047@frappe.validate_and_sanitize_search_inputs
Anand Doshibd67e872014-04-11 16:51:27 +053048def lead_query(doctype, txt, searchfield, start, page_len, filters):
Himanshud94a38e2020-05-18 14:26:26 +053049 fields = get_fields("Lead", ["name", "lead_name", "company_name"])
50
51 return frappe.db.sql("""select {fields} from `tabLead`
Anand Doshibd67e872014-04-11 16:51:27 +053052 where docstatus < 2
53 and ifnull(status, '') != 'Converted'
Anand Doshi48d3b542014-07-09 13:15:03 +053054 and ({key} like %(txt)s
55 or lead_name like %(txt)s
56 or company_name like %(txt)s)
57 {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +053058 order by
Anand Doshi48d3b542014-07-09 13:15:03 +053059 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
60 if(locate(%(_txt)s, lead_name), locate(%(_txt)s, lead_name), 99999),
61 if(locate(%(_txt)s, company_name), locate(%(_txt)s, company_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +053062 idx desc,
Anand Doshi652bc072014-04-16 15:21:46 +053063 name, lead_name
Anand Doshi48d3b542014-07-09 13:15:03 +053064 limit %(start)s, %(page_len)s""".format(**{
Himanshud94a38e2020-05-18 14:26:26 +053065 'fields': ", ".join(fields),
Anand Doshi48d3b542014-07-09 13:15:03 +053066 'key': searchfield,
67 'mcond':get_match_cond(doctype)
68 }), {
69 'txt': "%%%s%%" % txt,
70 '_txt': txt.replace("%", ""),
71 'start': start,
72 'page_len': page_len
73 })
Saurabh02875592013-07-08 18:45:55 +053074
Himanshud94a38e2020-05-18 14:26:26 +053075
Saurabh02875592013-07-08 18:45:55 +053076 # searches for customer
Chinmay D. Paiaa121092020-07-01 21:14:32 +053077@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +053078@frappe.validate_and_sanitize_search_inputs
Saurabh02875592013-07-08 18:45:55 +053079def customer_query(doctype, txt, searchfield, start, page_len, filters):
KanchanChauhan4b888b92017-07-25 14:03:01 +053080 conditions = []
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053081 cust_master_name = frappe.defaults.get_user_default("cust_master_name")
Saurabhf52dc072013-07-10 13:07:49 +053082
Saurabh02875592013-07-08 18:45:55 +053083 if cust_master_name == "Customer Name":
84 fields = ["name", "customer_group", "territory"]
85 else:
86 fields = ["name", "customer_name", "customer_group", "territory"]
Rushabh Mehtab92087c2017-01-13 18:53:11 +053087
Himanshud94a38e2020-05-18 14:26:26 +053088 fields = get_fields("Customer", fields)
Saurabhf52dc072013-07-10 13:07:49 +053089
Himanshud94a38e2020-05-18 14:26:26 +053090 searchfields = frappe.get_meta("Customer").get_search_fields()
Ankush Menata9c84f72021-06-11 16:00:48 +053091 searchfields = " or ".join(field + " like %(txt)s" for field in searchfields)
Saurabh02875592013-07-08 18:45:55 +053092
Anand Doshi48d3b542014-07-09 13:15:03 +053093 return frappe.db.sql("""select {fields} from `tabCustomer`
Anand Doshibd67e872014-04-11 16:51:27 +053094 where docstatus < 2
Console Admin86231662017-06-23 20:32:52 +030095 and ({scond}) and disabled=0
KanchanChauhan4b888b92017-07-25 14:03:01 +053096 {fcond} {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +053097 order by
Anand Doshi48d3b542014-07-09 13:15:03 +053098 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
99 if(locate(%(_txt)s, customer_name), locate(%(_txt)s, customer_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530100 idx desc,
Anand Doshibd67e872014-04-11 16:51:27 +0530101 name, customer_name
Anand Doshi48d3b542014-07-09 13:15:03 +0530102 limit %(start)s, %(page_len)s""".format(**{
Himanshud94a38e2020-05-18 14:26:26 +0530103 "fields": ", ".join(fields),
Console Admin86231662017-06-23 20:32:52 +0300104 "scond": searchfields,
KanchanChauhan4b888b92017-07-25 14:03:01 +0530105 "mcond": get_match_cond(doctype),
106 "fcond": get_filters_cond(doctype, filters, conditions).replace('%', '%%'),
Anand Doshi48d3b542014-07-09 13:15:03 +0530107 }), {
108 'txt': "%%%s%%" % txt,
109 '_txt': txt.replace("%", ""),
110 'start': start,
111 'page_len': page_len
112 })
Saurabh02875592013-07-08 18:45:55 +0530113
Himanshud94a38e2020-05-18 14:26:26 +0530114
Saurabh02875592013-07-08 18:45:55 +0530115# searches for supplier
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530116@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530117@frappe.validate_and_sanitize_search_inputs
Saurabh02875592013-07-08 18:45:55 +0530118def supplier_query(doctype, txt, searchfield, start, page_len, filters):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530119 supp_master_name = frappe.defaults.get_user_default("supp_master_name")
Suraj Shetty1923ef02020-08-05 19:42:25 +0530120
Anand Doshibd67e872014-04-11 16:51:27 +0530121 if supp_master_name == "Supplier Name":
Zlash652e080982018-04-19 18:37:53 +0530122 fields = ["name", "supplier_group"]
Anand Doshibd67e872014-04-11 16:51:27 +0530123 else:
Zlash652e080982018-04-19 18:37:53 +0530124 fields = ["name", "supplier_name", "supplier_group"]
Himanshud94a38e2020-05-18 14:26:26 +0530125
126 fields = get_fields("Supplier", fields)
Saurabh02875592013-07-08 18:45:55 +0530127
Anand Doshi48d3b542014-07-09 13:15:03 +0530128 return frappe.db.sql("""select {field} from `tabSupplier`
Anand Doshibd67e872014-04-11 16:51:27 +0530129 where docstatus < 2
Anand Doshi48d3b542014-07-09 13:15:03 +0530130 and ({key} like %(txt)s
shreyas29b565f2016-01-25 17:30:49 +0530131 or supplier_name like %(txt)s) and disabled=0
Anand Doshi48d3b542014-07-09 13:15:03 +0530132 {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +0530133 order by
Anand Doshi48d3b542014-07-09 13:15:03 +0530134 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
135 if(locate(%(_txt)s, supplier_name), locate(%(_txt)s, supplier_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530136 idx desc,
Anand Doshibd67e872014-04-11 16:51:27 +0530137 name, supplier_name
Anand Doshi48d3b542014-07-09 13:15:03 +0530138 limit %(start)s, %(page_len)s """.format(**{
Himanshud94a38e2020-05-18 14:26:26 +0530139 'field': ', '.join(fields),
Anand Doshi48d3b542014-07-09 13:15:03 +0530140 'key': searchfield,
141 'mcond':get_match_cond(doctype)
142 }), {
143 'txt': "%%%s%%" % txt,
144 '_txt': txt.replace("%", ""),
145 'start': start,
146 'page_len': page_len
147 })
Anand Doshibd67e872014-04-11 16:51:27 +0530148
Himanshud94a38e2020-05-18 14:26:26 +0530149
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530150@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530151@frappe.validate_and_sanitize_search_inputs
Nabin Hait9a380ef2013-07-16 17:24:17 +0530152def tax_account_query(doctype, txt, searchfield, start, page_len, filters):
Deepesh Gargfbf6e562020-03-31 10:45:32 +0530153 company_currency = erpnext.get_company_currency(filters.get('company'))
154
Suraj Shetty1923ef02020-08-05 19:42:25 +0530155 def get_accounts(with_account_type_filter):
156 account_type_condition = ''
157 if with_account_type_filter:
158 account_type_condition = "AND account_type in %(account_types)s"
159
160 accounts = frappe.db.sql("""
161 SELECT name, parent_account
162 FROM `tabAccount`
163 WHERE `tabAccount`.docstatus!=2
164 {account_type_condition}
165 AND is_group = 0
166 AND company = %(company)s
167 AND account_currency = %(currency)s
168 AND `{searchfield}` LIKE %(txt)s
prssannade7a2bc2020-09-21 13:57:04 +0530169 {mcond}
Suraj Shetty1923ef02020-08-05 19:42:25 +0530170 ORDER BY idx DESC, name
171 LIMIT %(offset)s, %(limit)s
prssannade7a2bc2020-09-21 13:57:04 +0530172 """.format(
173 account_type_condition=account_type_condition,
174 searchfield=searchfield,
175 mcond=get_match_cond(doctype)
176 ),
Suraj Shetty1923ef02020-08-05 19:42:25 +0530177 dict(
178 account_types=filters.get("account_type"),
179 company=filters.get("company"),
180 currency=company_currency,
181 txt="%{}%".format(txt),
182 offset=start,
183 limit=page_len
184 )
185 )
186
187 return accounts
188
189 tax_accounts = get_accounts(True)
190
Nabin Hait0c21e2a2014-03-21 11:14:49 +0530191 if not tax_accounts:
Suraj Shetty1923ef02020-08-05 19:42:25 +0530192 tax_accounts = get_accounts(False)
Anand Doshibd67e872014-04-11 16:51:27 +0530193
Nabin Hait0c21e2a2014-03-21 11:14:49 +0530194 return tax_accounts
Saurabh02875592013-07-08 18:45:55 +0530195
Himanshud94a38e2020-05-18 14:26:26 +0530196
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530197@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530198@frappe.validate_and_sanitize_search_inputs
Rushabh Mehta203cc962016-04-07 15:25:43 +0530199def item_query(doctype, txt, searchfield, start, page_len, filters, as_dict=False):
Saurabh02875592013-07-08 18:45:55 +0530200 conditions = []
Saurabhf52dc072013-07-10 13:07:49 +0530201
rohitwaghchaurec59371a2021-06-03 20:02:58 +0530202 if isinstance(filters, str):
203 filters = json.loads(filters)
204
marination3dbef9d2019-10-28 15:48:10 +0530205 #Get searchfields from meta and use in Item Link field query
marination1e754b12019-10-30 18:33:44 +0530206 meta = frappe.get_meta("Item", cached=True)
marination3dbef9d2019-10-28 15:48:10 +0530207 searchfields = meta.get_search_fields()
208
marination1e754b12019-10-30 18:33:44 +0530209 if "description" in searchfields:
210 searchfields.remove("description")
Rohit Waghchaure721b4132021-06-02 14:13:09 +0530211
Rohit Waghchaurec42312e2019-11-19 19:05:23 +0530212 columns = ''
213 extra_searchfields = [field for field in searchfields
214 if not field in ["name", "item_group", "description"]]
215
216 if extra_searchfields:
217 columns = ", " + ", ".join(extra_searchfields)
marination1e754b12019-10-30 18:33:44 +0530218
219 searchfields = searchfields + [field for field in[searchfield or "name", "item_code", "item_group", "item_name"]
220 if not field in searchfields]
marination3dbef9d2019-10-28 15:48:10 +0530221 searchfields = " or ".join([field + " like %(txt)s" for field in searchfields])
222
Rohit Waghchaure721b4132021-06-02 14:13:09 +0530223 if filters and isinstance(filters, dict) and filters.get('supplier'):
224 item_group_list = frappe.get_all('Supplier Item Group',
225 filters = {'supplier': filters.get('supplier')}, fields = ['item_group'])
226
noahjacobca2fb472021-05-12 16:25:07 +0530227 item_groups = []
228 for i in item_group_list:
229 item_groups.append(i.item_group)
230
231 del filters['supplier']
232
233 if item_groups:
234 filters['item_group'] = ['in', item_groups]
Rohit Waghchaure721b4132021-06-02 14:13:09 +0530235
Rushabh Mehtad5f9ebd2018-04-02 23:37:33 +0530236 description_cond = ''
237 if frappe.db.count('Item', cache=True) < 50000:
238 # scan description only if items are less than 50000
239 description_cond = 'or tabItem.description LIKE %(txt)s'
Prateeksha Singh984a7a72018-05-17 17:29:36 +0530240 return frappe.db.sql("""select tabItem.name,
Anand Doshibd67e872014-04-11 16:51:27 +0530241 if(length(tabItem.item_name) > 40,
242 concat(substr(tabItem.item_name, 1, 40), "..."), item_name) as item_name,
Prateeksha Singh984a7a72018-05-17 17:29:36 +0530243 tabItem.item_group,
Saurabh02875592013-07-08 18:45:55 +0530244 if(length(tabItem.description) > 40, \
Rohit Waghchaurec42312e2019-11-19 19:05:23 +0530245 concat(substr(tabItem.description, 1, 40), "..."), description) as description
marination1e754b12019-10-30 18:33:44 +0530246 {columns}
Anand Doshibd67e872014-04-11 16:51:27 +0530247 from tabItem
Anand Doshi22c0d782013-11-04 16:23:04 +0530248 where tabItem.docstatus < 2
Anand Doshi21e09a22015-10-29 12:21:41 +0530249 and tabItem.disabled=0
rohitwaghchaure79789072020-05-21 18:10:13 +0530250 and tabItem.has_variants=0
Rushabh Mehta864d1ea2014-06-23 12:20:12 +0530251 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 +0530252 and ({scond} or tabItem.item_code IN (select parent from `tabItem Barcode` where barcode LIKE %(txt)s)
Rohit Waghchaure2bfb0632019-03-02 21:47:55 +0530253 {description_cond})
Anand Doshi22c0d782013-11-04 16:23:04 +0530254 {fcond} {mcond}
Anand Doshi652bc072014-04-16 15:21:46 +0530255 order by
256 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
257 if(locate(%(_txt)s, item_name), locate(%(_txt)s, item_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530258 idx desc,
Anand Doshi652bc072014-04-16 15:21:46 +0530259 name, item_name
Rushabh Mehtabc4e2cd2017-10-17 12:30:34 +0530260 limit %(start)s, %(page_len)s """.format(
marination1e754b12019-10-30 18:33:44 +0530261 columns=columns,
marination3dbef9d2019-10-28 15:48:10 +0530262 scond=searchfields,
Nabin Haitc6285062016-03-30 13:10:25 +0530263 fcond=get_filters_cond(doctype, filters, conditions).replace('%', '%%'),
Rushabh Mehtad5f9ebd2018-04-02 23:37:33 +0530264 mcond=get_match_cond(doctype).replace('%', '%%'),
265 description_cond = description_cond),
Anand Doshi22c0d782013-11-04 16:23:04 +0530266 {
267 "today": nowdate(),
268 "txt": "%%%s%%" % txt,
Anand Doshi652bc072014-04-16 15:21:46 +0530269 "_txt": txt.replace("%", ""),
Anand Doshi22c0d782013-11-04 16:23:04 +0530270 "start": start,
271 "page_len": page_len
Rushabh Mehta203cc962016-04-07 15:25:43 +0530272 }, as_dict=as_dict)
Saurabh02875592013-07-08 18:45:55 +0530273
Himanshud94a38e2020-05-18 14:26:26 +0530274
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530275@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530276@frappe.validate_and_sanitize_search_inputs
Saurabh022ab632017-11-10 15:06:02 +0530277def bom(doctype, txt, searchfield, start, page_len, filters):
Anand Doshibd67e872014-04-11 16:51:27 +0530278 conditions = []
Himanshud94a38e2020-05-18 14:26:26 +0530279 fields = get_fields("BOM", ["name", "item"])
Saurabhf52dc072013-07-10 13:07:49 +0530280
Himanshud94a38e2020-05-18 14:26:26 +0530281 return frappe.db.sql("""select {fields}
Anand Doshibd67e872014-04-11 16:51:27 +0530282 from tabBOM
283 where tabBOM.docstatus=1
284 and tabBOM.is_active=1
Nabin Hait62211172016-03-16 16:22:03 +0530285 and tabBOM.`{key}` like %(txt)s
286 {fcond} {mcond}
287 order by
Rushabh Mehta3574b372016-03-11 14:33:04 +0530288 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
289 idx desc, name
Nabin Hait62211172016-03-16 16:22:03 +0530290 limit %(start)s, %(page_len)s """.format(
Himanshud94a38e2020-05-18 14:26:26 +0530291 fields=", ".join(fields),
Mangesh-Khairnar6a796912019-07-08 10:40:40 +0530292 fcond=get_filters_cond(doctype, filters, conditions).replace('%', '%%'),
Karthikeyan S747c2622019-07-19 22:49:21 +0530293 mcond=get_match_cond(doctype).replace('%', '%%'),
294 key=searchfield),
Mangesh-Khairnar6a796912019-07-08 10:40:40 +0530295 {
Karthikeyan S747c2622019-07-19 22:49:21 +0530296 'txt': '%' + txt + '%',
Rushabh Mehta3574b372016-03-11 14:33:04 +0530297 '_txt': txt.replace("%", ""),
Saurabh022ab632017-11-10 15:06:02 +0530298 'start': start or 0,
299 'page_len': page_len or 20
Rushabh Mehta3574b372016-03-11 14:33:04 +0530300 })
Saurabh02875592013-07-08 18:45:55 +0530301
Himanshud94a38e2020-05-18 14:26:26 +0530302
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530303@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530304@frappe.validate_and_sanitize_search_inputs
Saurabh02875592013-07-08 18:45:55 +0530305def get_project_name(doctype, txt, searchfield, start, page_len, filters):
306 cond = ''
Nabin Haitf71011a2014-08-21 11:34:31 +0530307 if filters.get('customer'):
Suraj Shetty6ea3de92018-09-26 18:15:53 +0530308 cond = """(`tabProject`.customer = %s or
rohitwaghchauree3304722018-08-27 11:43:57 +0530309 ifnull(`tabProject`.customer,"")="") and""" %(frappe.db.escape(filters.get("customer")))
Anand Doshibd67e872014-04-11 16:51:27 +0530310
Rucha Mahabal062d3012021-05-07 13:31:14 +0530311 fields = get_fields("Project", ["name", "project_name"])
312 searchfields = frappe.get_meta("Project").get_search_fields()
313 searchfields = " or ".join([field + " like %(txt)s" for field in searchfields])
Himanshud94a38e2020-05-18 14:26:26 +0530314
315 return frappe.db.sql("""select {fields} from `tabProject`
Rucha Mahabal062d3012021-05-07 13:31:14 +0530316 where
317 `tabProject`.status not in ("Completed", "Cancelled")
Subin Tom889140f2021-06-22 16:26:19 +0530318 and {cond} {scond} {match_cond}
Rushabh Mehta3574b372016-03-11 14:33:04 +0530319 order by
320 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
321 idx desc,
322 `tabProject`.name asc
323 limit {start}, {page_len}""".format(
Himanshud94a38e2020-05-18 14:26:26 +0530324 fields=", ".join(['`tabProject`.{0}'.format(f) for f in fields]),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530325 cond=cond,
Rucha Mahabal062d3012021-05-07 13:31:14 +0530326 scond=searchfields,
Rushabh Mehta3574b372016-03-11 14:33:04 +0530327 match_cond=get_match_cond(doctype),
328 start=start,
329 page_len=page_len), {
330 "txt": "%{0}%".format(txt),
Nabin Haitdf4deba2016-03-16 11:16:31 +0530331 "_txt": txt.replace('%', '')
Rushabh Mehta3574b372016-03-11 14:33:04 +0530332 })
Anand Doshibd67e872014-04-11 16:51:27 +0530333
tundebabzyf6d738b2017-09-18 12:40:09 +0100334
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530335@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530336@frappe.validate_and_sanitize_search_inputs
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530337def get_delivery_notes_to_be_billed(doctype, txt, searchfield, start, page_len, filters, as_dict):
Himanshud94a38e2020-05-18 14:26:26 +0530338 fields = get_fields("Delivery Note", ["name", "customer", "posting_date"])
339
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530340 return frappe.db.sql("""
Himanshud94a38e2020-05-18 14:26:26 +0530341 select %(fields)s
Anand Doshibd67e872014-04-11 16:51:27 +0530342 from `tabDelivery Note`
343 where `tabDelivery Note`.`%(key)s` like %(txt)s and
tundebabzyf6d738b2017-09-18 12:40:09 +0100344 `tabDelivery Note`.docstatus = 1
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530345 and status not in ("Stopped", "Closed") %(fcond)s
tundebabzyf6d738b2017-09-18 12:40:09 +0100346 and (
347 (`tabDelivery Note`.is_return = 0 and `tabDelivery Note`.per_billed < 100)
Deepesh Garge2dc1022021-04-14 11:21:11 +0530348 or (`tabDelivery Note`.grand_total = 0 and `tabDelivery Note`.per_billed < 100)
tundebabzyf6d738b2017-09-18 12:40:09 +0100349 or (
350 `tabDelivery Note`.is_return = 1
351 and return_against in (select name from `tabDelivery Note` where per_billed < 100)
352 )
353 )
rohitwaghchaured07a3e12019-05-15 07:46:28 +0530354 %(mcond)s order by `tabDelivery Note`.`%(key)s` asc limit %(start)s, %(page_len)s
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530355 """ % {
Himanshud94a38e2020-05-18 14:26:26 +0530356 "fields": ", ".join(["`tabDelivery Note`.{0}".format(f) for f in fields]),
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530357 "key": searchfield,
358 "fcond": get_filters_cond(doctype, filters, []),
359 "mcond": get_match_cond(doctype),
rohitwaghchaured07a3e12019-05-15 07:46:28 +0530360 "start": start,
361 "page_len": page_len,
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530362 "txt": "%(txt)s"
tundebabzyf6d738b2017-09-18 12:40:09 +0100363 }, {"txt": ("%%%s%%" % txt)}, as_dict=as_dict)
364
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530365
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530366@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530367@frappe.validate_and_sanitize_search_inputs
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530368def get_batch_no(doctype, txt, searchfield, start, page_len, filters):
Neil Trini Lasradoebb60f52015-07-08 14:36:09 +0530369 cond = ""
370 if filters.get("posting_date"):
Nabin Hait7918b922018-01-31 15:30:03 +0530371 cond = "and (batch.expiry_date is null or batch.expiry_date >= %(posting_date)s)"
Rushabh Mehtab6398be2015-08-26 10:50:16 +0530372
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530373 batch_nos = None
374 args = {
375 'item_code': filters.get("item_code"),
376 'warehouse': filters.get("warehouse"),
377 'posting_date': filters.get('posting_date'),
Anand Doshi0dc79f42015-04-06 12:59:34 +0530378 'txt': "%{0}%".format(txt),
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530379 "start": start,
380 "page_len": page_len
381 }
382
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530383 having_clause = "having sum(sle.actual_qty) > 0"
384 if filters.get("is_return"):
385 having_clause = ""
386
Deepesh Garga0d192e2020-09-22 13:54:07 +0530387 meta = frappe.get_meta("Batch", cached=True)
388 searchfields = meta.get_search_fields()
389
390 search_columns = ''
Deepesh Gargf58a5ec2020-10-05 13:55:53 +0530391 search_cond = ''
392
Deepesh Garga0d192e2020-09-22 13:54:07 +0530393 if searchfields:
394 search_columns = ", " + ", ".join(searchfields)
Deepesh Garg1fae7742020-10-05 12:38:54 +0530395 search_cond = " or " + " or ".join([field + " like %(txt)s" for field in searchfields])
Deepesh Garga0d192e2020-09-22 13:54:07 +0530396
Anand Doshi0dc79f42015-04-06 12:59:34 +0530397 if args.get('warehouse'):
Deepesh Garga0d192e2020-09-22 13:54:07 +0530398 searchfields = ['batch.' + field for field in searchfields]
399 if searchfields:
400 search_columns = ", " + ", ".join(searchfields)
Deepesh Garg1fae7742020-10-05 12:38:54 +0530401 search_cond = " or " + " or ".join([field + " like %(txt)s" for field in searchfields])
Deepesh Garga0d192e2020-09-22 13:54:07 +0530402
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530403 batch_nos = frappe.db.sql("""select sle.batch_no, round(sum(sle.actual_qty),2), sle.stock_uom,
404 concat('MFG-',batch.manufacturing_date), concat('EXP-',batch.expiry_date)
Deepesh Garga0d192e2020-09-22 13:54:07 +0530405 {search_columns}
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530406 from `tabStock Ledger Entry` sle
407 INNER JOIN `tabBatch` batch on sle.batch_no = batch.name
408 where
409 batch.disabled = 0
Rohit Waghchaurec14aa452021-07-20 18:19:15 +0530410 and sle.is_cancelled = 0
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530411 and sle.item_code = %(item_code)s
412 and sle.warehouse = %(warehouse)s
413 and (sle.batch_no like %(txt)s
Sun Howwrongbum088be372019-12-24 12:29:25 +0530414 or batch.expiry_date like %(txt)s
Deepesh Gargf58a5ec2020-10-05 13:55:53 +0530415 or batch.manufacturing_date like %(txt)s
416 {search_cond})
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530417 and batch.docstatus < 2
418 {cond}
419 {match_conditions}
420 group by batch_no {having_clause}
421 order by batch.expiry_date, sle.batch_no desc
422 limit %(start)s, %(page_len)s""".format(
Deepesh Garga0d192e2020-09-22 13:54:07 +0530423 search_columns = search_columns,
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530424 cond=cond,
425 match_conditions=get_match_cond(doctype),
Deepesh Garg1fae7742020-10-05 12:38:54 +0530426 having_clause = having_clause,
427 search_cond = search_cond
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530428 ), args)
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530429
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530430 return batch_nos
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530431 else:
Deepesh Garga0d192e2020-09-22 13:54:07 +0530432 return frappe.db.sql("""select name, concat('MFG-', manufacturing_date), concat('EXP-',expiry_date)
433 {search_columns}
434 from `tabBatch` batch
Doridel Cahanap59e4c322018-08-06 17:15:18 +0800435 where batch.disabled = 0
436 and item = %(item_code)s
sivankar621740e2018-02-12 14:33:40 +0530437 and (name like %(txt)s
Sun Howwrongbum088be372019-12-24 12:29:25 +0530438 or expiry_date like %(txt)s
Deepesh Gargf58a5ec2020-10-05 13:55:53 +0530439 or manufacturing_date like %(txt)s
440 {search_cond})
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530441 and docstatus < 2
Neil Trini Lasradoebb60f52015-07-08 14:36:09 +0530442 {0}
Anand Doshi0dc79f42015-04-06 12:59:34 +0530443 {match_conditions}
Deepesh Gargf58a5ec2020-10-05 13:55:53 +0530444
Anand Doshi0dc79f42015-04-06 12:59:34 +0530445 order by expiry_date, name desc
Deepesh Garg1fae7742020-10-05 12:38:54 +0530446 limit %(start)s, %(page_len)s""".format(cond, search_columns = search_columns,
447 search_cond = search_cond, match_conditions=get_match_cond(doctype)), args)
Nabin Haitea4aa042014-05-28 12:56:28 +0530448
Himanshud94a38e2020-05-18 14:26:26 +0530449
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530450@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530451@frappe.validate_and_sanitize_search_inputs
Nabin Haitea4aa042014-05-28 12:56:28 +0530452def get_account_list(doctype, txt, searchfield, start, page_len, filters):
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530453 filter_list = []
Nabin Haitea4aa042014-05-28 12:56:28 +0530454
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530455 if isinstance(filters, dict):
456 for key, val in filters.items():
457 if isinstance(val, (list, tuple)):
458 filter_list.append([doctype, key, val[0], val[1]])
459 else:
460 filter_list.append([doctype, key, "=", val])
bhupeshg2e2e973f2015-04-14 22:15:24 +0530461 elif isinstance(filters, list):
462 filter_list.extend(filters)
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530463
Rushabh Mehta38c6b522015-04-23 13:14:17 +0530464 if "is_group" not in [d[1] for d in filter_list]:
465 filter_list.append(["Account", "is_group", "=", "0"])
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530466
467 if searchfield and txt:
468 filter_list.append([doctype, searchfield, "like", "%%%s%%" % txt])
469
Rushabh Mehtac0bb4532014-09-09 16:15:35 +0530470 return frappe.desk.reportview.execute("Account", filters = filter_list,
Nabin Haitea4aa042014-05-28 12:56:28 +0530471 fields = ["name", "parent_account"],
472 limit_start=start, limit_page_length=page_len, as_list=True)
Anand Doshifaefeaa2014-06-24 18:53:04 +0530473
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530474@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530475@frappe.validate_and_sanitize_search_inputs
Marica299e2172020-04-28 13:00:04 +0530476def get_blanket_orders(doctype, txt, searchfield, start, page_len, filters):
477 return frappe.db.sql("""select distinct bo.name, bo.blanket_order_type, bo.to_date
478 from `tabBlanket Order` bo, `tabBlanket Order Item` boi
479 where
480 boi.parent = bo.name
481 and boi.item_code = {item_code}
482 and bo.blanket_order_type = '{blanket_order_type}'
483 and bo.company = {company}
484 and bo.docstatus = 1"""
485 .format(item_code = frappe.db.escape(filters.get("item")),
486 blanket_order_type = filters.get("blanket_order_type"),
487 company = frappe.db.escape(filters.get("company"))
488 ))
Nabin Haitafd14f62015-10-19 11:55:28 +0530489
Himanshud94a38e2020-05-18 14:26:26 +0530490
Nabin Haitafd14f62015-10-19 11:55:28 +0530491@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530492@frappe.validate_and_sanitize_search_inputs
Nabin Haitafd14f62015-10-19 11:55:28 +0530493def get_income_account(doctype, txt, searchfield, start, page_len, filters):
494 from erpnext.controllers.queries import get_match_cond
495
496 # income account can be any Credit account,
497 # but can also be a Asset account with account_type='Income Account' in special circumstances.
498 # Hence the first condition is an "OR"
499 if not filters: filters = {}
500
Anand Doshi21e09a22015-10-29 12:21:41 +0530501 condition = ""
Nabin Haitafd14f62015-10-19 11:55:28 +0530502 if filters.get("company"):
503 condition += "and tabAccount.company = %(company)s"
Anand Doshi21e09a22015-10-29 12:21:41 +0530504
Nabin Haitafd14f62015-10-19 11:55:28 +0530505 return frappe.db.sql("""select tabAccount.name from `tabAccount`
506 where (tabAccount.report_type = "Profit and Loss"
507 or tabAccount.account_type in ("Income Account", "Temporary"))
508 and tabAccount.is_group=0
509 and tabAccount.`{key}` LIKE %(txt)s
Rushabh Mehta3574b372016-03-11 14:33:04 +0530510 {condition} {match_condition}
511 order by idx desc, name"""
Nabin Haitafd14f62015-10-19 11:55:28 +0530512 .format(condition=condition, match_condition=get_match_cond(doctype), key=searchfield), {
Suraj Shetty4b404c42018-09-27 15:39:34 +0530513 'txt': '%' + txt + '%',
Nabin Haitafd14f62015-10-19 11:55:28 +0530514 'company': filters.get("company", "")
Anand Doshi21e09a22015-10-29 12:21:41 +0530515 })
Nabin Hait3a15c922016-03-04 12:30:46 +0530516
Deepesh Garg96e874b2020-11-15 22:43:01 +0530517@frappe.whitelist()
518@frappe.validate_and_sanitize_search_inputs
519def get_filtered_dimensions(doctype, txt, searchfield, start, page_len, filters):
520 from erpnext.accounts.doctype.accounting_dimension_filter.accounting_dimension_filter import get_dimension_filter_map
521 dimension_filters = get_dimension_filter_map()
522 dimension_filters = dimension_filters.get((filters.get('dimension'),filters.get('account')))
Deepesh Garg6c17b842020-11-25 13:42:16 +0530523 query_filters = []
Deepesh Garg96e874b2020-11-15 22:43:01 +0530524
525 meta = frappe.get_meta(doctype)
Deepesh Garg96e874b2020-11-15 22:43:01 +0530526 if meta.is_tree:
Deepesh Garg6c17b842020-11-25 13:42:16 +0530527 query_filters.append(['is_group', '=', 0])
Deepesh Garg96e874b2020-11-15 22:43:01 +0530528
529 if meta.has_field('company'):
Deepesh Garg6c17b842020-11-25 13:42:16 +0530530 query_filters.append(['company', '=', filters.get('company')])
531
532 if txt:
533 query_filters.append([searchfield, 'LIKE', "%%%s%%" % txt])
Deepesh Garg96e874b2020-11-15 22:43:01 +0530534
535 if dimension_filters:
536 if dimension_filters['allow_or_restrict'] == 'Allow':
537 query_selector = 'in'
538 else:
539 query_selector = 'not in'
540
541 if len(dimension_filters['allowed_dimensions']) == 1:
542 dimensions = tuple(dimension_filters['allowed_dimensions'] * 2)
543 else:
544 dimensions = tuple(dimension_filters['allowed_dimensions'])
545
Deepesh Garg6c17b842020-11-25 13:42:16 +0530546 query_filters.append(['name', query_selector, dimensions])
Deepesh Garg96e874b2020-11-15 22:43:01 +0530547
Deepesh Garg6c17b842020-11-25 13:42:16 +0530548 output = frappe.get_all(doctype, filters=query_filters)
549 result = [d.name for d in output]
550
551 return [(d,) for d in set(result)]
Nabin Hait3a15c922016-03-04 12:30:46 +0530552
553@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530554@frappe.validate_and_sanitize_search_inputs
Nabin Hait3a15c922016-03-04 12:30:46 +0530555def get_expense_account(doctype, txt, searchfield, start, page_len, filters):
556 from erpnext.controllers.queries import get_match_cond
Rushabh Mehta203cc962016-04-07 15:25:43 +0530557
Nabin Hait3a15c922016-03-04 12:30:46 +0530558 if not filters: filters = {}
559
560 condition = ""
561 if filters.get("company"):
562 condition += "and tabAccount.company = %(company)s"
Rushabh Mehta203cc962016-04-07 15:25:43 +0530563
Nabin Hait3a15c922016-03-04 12:30:46 +0530564 return frappe.db.sql("""select tabAccount.name from `tabAccount`
565 where (tabAccount.report_type = "Profit and Loss"
Mangesh-Khairnar5619db22019-08-21 14:49:24 +0530566 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 +0530567 and tabAccount.is_group=0
568 and tabAccount.docstatus!=2
569 and tabAccount.{key} LIKE %(txt)s
570 {condition} {match_condition}"""
Suraj Shettybfc195d2018-09-21 10:20:52 +0530571 .format(condition=condition, key=searchfield,
Nabin Hait3a15c922016-03-04 12:30:46 +0530572 match_condition=get_match_cond(doctype)), {
Neil Trini Lasrado30b97b02016-03-31 23:10:13 +0530573 'company': filters.get("company", ""),
Suraj Shetty4b404c42018-09-27 15:39:34 +0530574 'txt': '%' + txt + '%'
Maxwell Morais35572612016-07-21 23:42:59 -0300575 })
suyashphadtare049a88c2017-01-12 17:49:37 +0530576
577
578@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530579@frappe.validate_and_sanitize_search_inputs
suyashphadtare049a88c2017-01-12 17:49:37 +0530580def warehouse_query(doctype, txt, searchfield, start, page_len, filters):
581 # Should be used when item code is passed in filters.
suyashphadtare750a0672017-01-18 15:35:01 +0530582 conditions, bin_conditions = [], []
583 filter_dict = get_doctype_wise_filters(filters)
584
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530585 query = """select `tabWarehouse`.name,
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530586 CONCAT_WS(" : ", "Actual Qty", ifnull(round(`tabBin`.actual_qty, 2), 0 )) actual_qty
587 from `tabWarehouse` left join `tabBin`
588 on `tabBin`.warehouse = `tabWarehouse`.name {bin_conditions}
suyashphadtare34ab1362017-01-31 15:14:44 +0530589 where
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530590 `tabWarehouse`.`{key}` like {txt}
suyashphadtare34ab1362017-01-31 15:14:44 +0530591 {fcond} {mcond}
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530592 order by ifnull(`tabBin`.actual_qty, 0) desc
suyashphadtare34ab1362017-01-31 15:14:44 +0530593 limit
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530594 {start}, {page_len}
suyashphadtare34ab1362017-01-31 15:14:44 +0530595 """.format(
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530596 bin_conditions=get_filters_cond(doctype, filter_dict.get("Bin"),bin_conditions, ignore_permissions=True),
Suraj Shettybfc195d2018-09-21 10:20:52 +0530597 key=searchfield,
suyashphadtare34ab1362017-01-31 15:14:44 +0530598 fcond=get_filters_cond(doctype, filter_dict.get("Warehouse"), conditions),
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530599 mcond=get_match_cond(doctype),
600 start=start,
601 page_len=page_len,
602 txt=frappe.db.escape('%{0}%'.format(txt))
603 )
604
605 return frappe.db.sql(query)
suyashphadtare750a0672017-01-18 15:35:01 +0530606
607
608def get_doctype_wise_filters(filters):
609 # Helper function to seperate filters doctype_wise
610 filter_dict = defaultdict(list)
611 for row in filters:
612 filter_dict[row[0]].append(row)
613 return filter_dict
tundebabzy2a4fefc2017-11-29 06:23:09 +0100614
615
616@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530617@frappe.validate_and_sanitize_search_inputs
tundebabzy2a4fefc2017-11-29 06:23:09 +0100618def get_batch_numbers(doctype, txt, searchfield, start, page_len, filters):
rohitwaghchaure9fbed562018-01-12 16:22:33 +0530619 query = """select batch_id from `tabBatch`
Doridel Cahanap59e4c322018-08-06 17:15:18 +0800620 where disabled = 0
621 and (expiry_date >= CURDATE() or expiry_date IS NULL)
Suraj Shettybfc195d2018-09-21 10:20:52 +0530622 and name like {txt}""".format(txt = frappe.db.escape('%{0}%'.format(txt)))
tundebabzy2a4fefc2017-11-29 06:23:09 +0100623
rohitwaghchaure9fbed562018-01-12 16:22:33 +0530624 if filters and filters.get('item'):
Suraj Shettybfc195d2018-09-21 10:20:52 +0530625 query += " and item = {item}".format(item = frappe.db.escape(filters.get('item')))
tundebabzy2a4fefc2017-11-29 06:23:09 +0100626
Sachin Mane64f48db2018-01-08 17:57:32 +0530627 return frappe.db.sql(query, filters)
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530628
Himanshud94a38e2020-05-18 14:26:26 +0530629
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530630@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530631@frappe.validate_and_sanitize_search_inputs
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530632def item_manufacturer_query(doctype, txt, searchfield, start, page_len, filters):
Maricabac4b932019-09-16 19:44:28 +0530633 item_filters = [
634 ['manufacturer', 'like', '%' + txt + '%'],
635 ['item_code', '=', filters.get("item_code")]
636 ]
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530637
Maricabac4b932019-09-16 19:44:28 +0530638 item_manufacturers = frappe.get_all(
639 "Item Manufacturer",
640 fields=["manufacturer", "manufacturer_part_no"],
641 filters=item_filters,
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530642 limit_start=start,
643 limit_page_length=page_len,
644 as_list=1
645 )
Maricabac4b932019-09-16 19:44:28 +0530646 return item_manufacturers
Saqibd9956092019-11-18 11:46:55 +0530647
Himanshud94a38e2020-05-18 14:26:26 +0530648
Saqibd9956092019-11-18 11:46:55 +0530649@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530650@frappe.validate_and_sanitize_search_inputs
Saqibd9956092019-11-18 11:46:55 +0530651def get_purchase_receipts(doctype, txt, searchfield, start, page_len, filters):
652 query = """
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530653 select pr.name
Saqibd9956092019-11-18 11:46:55 +0530654 from `tabPurchase Receipt` pr, `tabPurchase Receipt Item` pritem
655 where pr.docstatus = 1 and pritem.parent = pr.name
656 and pr.name like {txt}""".format(txt = frappe.db.escape('%{0}%'.format(txt)))
657
658 if filters and filters.get('item_code'):
659 query += " and pritem.item_code = {item_code}".format(item_code = frappe.db.escape(filters.get('item_code')))
660
661 return frappe.db.sql(query, filters)
662
Himanshud94a38e2020-05-18 14:26:26 +0530663
Saqibd9956092019-11-18 11:46:55 +0530664@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530665@frappe.validate_and_sanitize_search_inputs
Saqibd9956092019-11-18 11:46:55 +0530666def get_purchase_invoices(doctype, txt, searchfield, start, page_len, filters):
667 query = """
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530668 select pi.name
Saqibd9956092019-11-18 11:46:55 +0530669 from `tabPurchase Invoice` pi, `tabPurchase Invoice Item` piitem
670 where pi.docstatus = 1 and piitem.parent = pi.name
671 and pi.name like {txt}""".format(txt = frappe.db.escape('%{0}%'.format(txt)))
672
673 if filters and filters.get('item_code'):
674 query += " and piitem.item_code = {item_code}".format(item_code = frappe.db.escape(filters.get('item_code')))
675
676 return frappe.db.sql(query, filters)
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530677
Himanshud94a38e2020-05-18 14:26:26 +0530678
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530679@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530680@frappe.validate_and_sanitize_search_inputs
Rucha Mahabal20e53152021-01-18 14:56:55 +0530681def get_healthcare_service_units(doctype, txt, searchfield, start, page_len, filters):
682 query = """
683 select name
684 from `tabHealthcare Service Unit`
685 where
686 is_group = 0
687 and company = {company}
688 and name like {txt}""".format(
689 company = frappe.db.escape(filters.get('company')), txt = frappe.db.escape('%{0}%'.format(txt)))
690
691 if filters and filters.get('inpatient_record'):
692 from erpnext.healthcare.doctype.inpatient_medication_entry.inpatient_medication_entry import get_current_healthcare_service_unit
693 service_unit = get_current_healthcare_service_unit(filters.get('inpatient_record'))
694
695 # if the patient is admitted, then appointments should be allowed against the admission service unit,
696 # inspite of it being an Inpatient Occupancy service unit
697 if service_unit:
698 query += " and (allow_appointments = 1 or name = {service_unit})".format(service_unit = frappe.db.escape(service_unit))
699 else:
700 query += " and allow_appointments = 1"
701 else:
702 query += " and allow_appointments = 1"
703
704 return frappe.db.sql(query, filters)
705
706
707@frappe.whitelist()
708@frappe.validate_and_sanitize_search_inputs
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530709def get_tax_template(doctype, txt, searchfield, start, page_len, filters):
710
711 item_doc = frappe.get_cached_doc('Item', filters.get('item_code'))
712 item_group = filters.get('item_group')
713 taxes = item_doc.taxes or []
714
715 while item_group:
716 item_group_doc = frappe.get_cached_doc('Item Group', item_group)
717 taxes += item_group_doc.taxes or []
718 item_group = item_group_doc.parent_item_group
719
720 if not taxes:
721 return frappe.db.sql(""" SELECT name FROM `tabItem Tax Template` """)
722 else:
Marica0fcb05a2020-08-10 14:48:13 +0530723 valid_from = filters.get('valid_from')
724 valid_from = valid_from[1] if isinstance(valid_from, list) else valid_from
725
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530726 args = {
727 'item_code': filters.get('item_code'),
Marica0fcb05a2020-08-10 14:48:13 +0530728 'posting_date': valid_from,
mohammadahmad199041c0c9f2020-06-18 11:18:44 +0500729 'tax_category': filters.get('tax_category'),
730 'company': filters.get('company')
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530731 }
732
733 taxes = _get_item_tax_template(args, taxes, for_validate=True)
734 return [(d,) for d in set(taxes)]
Himanshud94a38e2020-05-18 14:26:26 +0530735
736
Ankush Menat7eac4a22021-04-19 10:33:39 +0530737def get_fields(doctype, fields=None):
738 if fields is None:
739 fields = []
Himanshud94a38e2020-05-18 14:26:26 +0530740 meta = frappe.get_meta(doctype)
741 fields.extend(meta.get_search_fields())
742
743 if meta.title_field and not meta.title_field.strip() in fields:
744 fields.insert(1, meta.title_field.strip())
745
746 return unique(fields)