blob: b31724fa4879be15303bc87e57a711bdd22eb934 [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
Rushabh Mehtab92087c2017-01-13 18:53:11 +05307from frappe.desk.reportview import get_match_cond, get_filters_cond
Deepesh Gargef0d26c2020-01-06 15:34:15 +05308from frappe.utils import nowdate, getdate
suyashphadtare750a0672017-01-18 15:35:01 +05309from collections import defaultdict
Deepesh Gargef0d26c2020-01-06 15:34:15 +053010from erpnext.stock.get_item_details import _get_item_tax_template
Himanshud94a38e2020-05-18 14:26:26 +053011from frappe.utils import unique
Saurabh02875592013-07-08 18:45:55 +053012
Chinmay D. Paiaa121092020-07-01 21:14:32 +053013# searches for active employees
14@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +053015@frappe.validate_and_sanitize_search_inputs
Saurabh02875592013-07-08 18:45:55 +053016def employee_query(doctype, txt, searchfield, start, page_len, filters):
Kanchan Chauhan7652b852016-11-16 15:29:01 +053017 conditions = []
Himanshud94a38e2020-05-18 14:26:26 +053018 fields = get_fields("Employee", ["name", "employee_name"])
19
20 return frappe.db.sql("""select {fields} from `tabEmployee`
Anand Doshibd67e872014-04-11 16:51:27 +053021 where status = 'Active'
22 and docstatus < 2
Anand Doshi48d3b542014-07-09 13:15:03 +053023 and ({key} like %(txt)s
24 or employee_name like %(txt)s)
Kanchan Chauhan7652b852016-11-16 15:29:01 +053025 {fcond} {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +053026 order by
Anand Doshi48d3b542014-07-09 13:15:03 +053027 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
28 if(locate(%(_txt)s, employee_name), locate(%(_txt)s, employee_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +053029 idx desc,
Anand Doshi652bc072014-04-16 15:21:46 +053030 name, employee_name
Anand Doshi48d3b542014-07-09 13:15:03 +053031 limit %(start)s, %(page_len)s""".format(**{
Himanshud94a38e2020-05-18 14:26:26 +053032 'fields': ", ".join(fields),
Anand Doshi48d3b542014-07-09 13:15:03 +053033 'key': searchfield,
Kanchan Chauhan7652b852016-11-16 15:29:01 +053034 'fcond': get_filters_cond(doctype, filters, conditions),
Anand Doshi48d3b542014-07-09 13:15:03 +053035 'mcond': get_match_cond(doctype)
36 }), {
37 'txt': "%%%s%%" % txt,
38 '_txt': txt.replace("%", ""),
39 'start': start,
40 'page_len': page_len
41 })
Saurabh02875592013-07-08 18:45:55 +053042
Himanshud94a38e2020-05-18 14:26:26 +053043
44# searches for leads which are not converted
Chinmay D. Paiaa121092020-07-01 21:14:32 +053045@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +053046@frappe.validate_and_sanitize_search_inputs
Anand Doshibd67e872014-04-11 16:51:27 +053047def lead_query(doctype, txt, searchfield, start, page_len, filters):
Himanshud94a38e2020-05-18 14:26:26 +053048 fields = get_fields("Lead", ["name", "lead_name", "company_name"])
49
50 return frappe.db.sql("""select {fields} from `tabLead`
Anand Doshibd67e872014-04-11 16:51:27 +053051 where docstatus < 2
52 and ifnull(status, '') != 'Converted'
Anand Doshi48d3b542014-07-09 13:15:03 +053053 and ({key} like %(txt)s
54 or lead_name like %(txt)s
55 or company_name like %(txt)s)
56 {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +053057 order by
Anand Doshi48d3b542014-07-09 13:15:03 +053058 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
59 if(locate(%(_txt)s, lead_name), locate(%(_txt)s, lead_name), 99999),
60 if(locate(%(_txt)s, company_name), locate(%(_txt)s, company_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +053061 idx desc,
Anand Doshi652bc072014-04-16 15:21:46 +053062 name, lead_name
Anand Doshi48d3b542014-07-09 13:15:03 +053063 limit %(start)s, %(page_len)s""".format(**{
Himanshud94a38e2020-05-18 14:26:26 +053064 'fields': ", ".join(fields),
Anand Doshi48d3b542014-07-09 13:15:03 +053065 'key': searchfield,
66 'mcond':get_match_cond(doctype)
67 }), {
68 'txt': "%%%s%%" % txt,
69 '_txt': txt.replace("%", ""),
70 'start': start,
71 'page_len': page_len
72 })
Saurabh02875592013-07-08 18:45:55 +053073
Himanshud94a38e2020-05-18 14:26:26 +053074
Saurabh02875592013-07-08 18:45:55 +053075 # searches for customer
Chinmay D. Paiaa121092020-07-01 21:14:32 +053076@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +053077@frappe.validate_and_sanitize_search_inputs
Saurabh02875592013-07-08 18:45:55 +053078def customer_query(doctype, txt, searchfield, start, page_len, filters):
KanchanChauhan4b888b92017-07-25 14:03:01 +053079 conditions = []
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053080 cust_master_name = frappe.defaults.get_user_default("cust_master_name")
Saurabhf52dc072013-07-10 13:07:49 +053081
Saurabh02875592013-07-08 18:45:55 +053082 if cust_master_name == "Customer Name":
83 fields = ["name", "customer_group", "territory"]
84 else:
85 fields = ["name", "customer_name", "customer_group", "territory"]
Rushabh Mehtab92087c2017-01-13 18:53:11 +053086
Himanshud94a38e2020-05-18 14:26:26 +053087 fields = get_fields("Customer", fields)
Saurabhf52dc072013-07-10 13:07:49 +053088
Himanshud94a38e2020-05-18 14:26:26 +053089 searchfields = frappe.get_meta("Customer").get_search_fields()
Console Admin86231662017-06-23 20:32:52 +030090 searchfields = " or ".join([field + " like %(txt)s" for field in searchfields])
Saurabh02875592013-07-08 18:45:55 +053091
Anand Doshi48d3b542014-07-09 13:15:03 +053092 return frappe.db.sql("""select {fields} from `tabCustomer`
Anand Doshibd67e872014-04-11 16:51:27 +053093 where docstatus < 2
Console Admin86231662017-06-23 20:32:52 +030094 and ({scond}) and disabled=0
KanchanChauhan4b888b92017-07-25 14:03:01 +053095 {fcond} {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +053096 order by
Anand Doshi48d3b542014-07-09 13:15:03 +053097 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
98 if(locate(%(_txt)s, customer_name), locate(%(_txt)s, customer_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +053099 idx desc,
Anand Doshibd67e872014-04-11 16:51:27 +0530100 name, customer_name
Anand Doshi48d3b542014-07-09 13:15:03 +0530101 limit %(start)s, %(page_len)s""".format(**{
Himanshud94a38e2020-05-18 14:26:26 +0530102 "fields": ", ".join(fields),
Console Admin86231662017-06-23 20:32:52 +0300103 "scond": searchfields,
KanchanChauhan4b888b92017-07-25 14:03:01 +0530104 "mcond": get_match_cond(doctype),
105 "fcond": get_filters_cond(doctype, filters, conditions).replace('%', '%%'),
Anand Doshi48d3b542014-07-09 13:15:03 +0530106 }), {
107 'txt': "%%%s%%" % txt,
108 '_txt': txt.replace("%", ""),
109 'start': start,
110 'page_len': page_len
111 })
Saurabh02875592013-07-08 18:45:55 +0530112
Himanshud94a38e2020-05-18 14:26:26 +0530113
Saurabh02875592013-07-08 18:45:55 +0530114# searches for supplier
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530115@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530116@frappe.validate_and_sanitize_search_inputs
Saurabh02875592013-07-08 18:45:55 +0530117def supplier_query(doctype, txt, searchfield, start, page_len, filters):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530118 supp_master_name = frappe.defaults.get_user_default("supp_master_name")
Suraj Shetty1923ef02020-08-05 19:42:25 +0530119
Anand Doshibd67e872014-04-11 16:51:27 +0530120 if supp_master_name == "Supplier Name":
Zlash652e080982018-04-19 18:37:53 +0530121 fields = ["name", "supplier_group"]
Anand Doshibd67e872014-04-11 16:51:27 +0530122 else:
Zlash652e080982018-04-19 18:37:53 +0530123 fields = ["name", "supplier_name", "supplier_group"]
Himanshud94a38e2020-05-18 14:26:26 +0530124
125 fields = get_fields("Supplier", fields)
Saurabh02875592013-07-08 18:45:55 +0530126
Anand Doshi48d3b542014-07-09 13:15:03 +0530127 return frappe.db.sql("""select {field} from `tabSupplier`
Anand Doshibd67e872014-04-11 16:51:27 +0530128 where docstatus < 2
Anand Doshi48d3b542014-07-09 13:15:03 +0530129 and ({key} like %(txt)s
shreyas29b565f2016-01-25 17:30:49 +0530130 or supplier_name like %(txt)s) and disabled=0
Anand Doshi48d3b542014-07-09 13:15:03 +0530131 {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +0530132 order by
Anand Doshi48d3b542014-07-09 13:15:03 +0530133 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
134 if(locate(%(_txt)s, supplier_name), locate(%(_txt)s, supplier_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530135 idx desc,
Anand Doshibd67e872014-04-11 16:51:27 +0530136 name, supplier_name
Anand Doshi48d3b542014-07-09 13:15:03 +0530137 limit %(start)s, %(page_len)s """.format(**{
Himanshud94a38e2020-05-18 14:26:26 +0530138 'field': ', '.join(fields),
Anand Doshi48d3b542014-07-09 13:15:03 +0530139 'key': searchfield,
140 'mcond':get_match_cond(doctype)
141 }), {
142 'txt': "%%%s%%" % txt,
143 '_txt': txt.replace("%", ""),
144 'start': start,
145 'page_len': page_len
146 })
Anand Doshibd67e872014-04-11 16:51:27 +0530147
Himanshud94a38e2020-05-18 14:26:26 +0530148
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530149@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530150@frappe.validate_and_sanitize_search_inputs
Nabin Hait9a380ef2013-07-16 17:24:17 +0530151def tax_account_query(doctype, txt, searchfield, start, page_len, filters):
Deepesh Gargfbf6e562020-03-31 10:45:32 +0530152 company_currency = erpnext.get_company_currency(filters.get('company'))
153
Suraj Shetty1923ef02020-08-05 19:42:25 +0530154 def get_accounts(with_account_type_filter):
155 account_type_condition = ''
156 if with_account_type_filter:
157 account_type_condition = "AND account_type in %(account_types)s"
158
159 accounts = frappe.db.sql("""
160 SELECT name, parent_account
161 FROM `tabAccount`
162 WHERE `tabAccount`.docstatus!=2
163 {account_type_condition}
164 AND is_group = 0
165 AND company = %(company)s
166 AND account_currency = %(currency)s
167 AND `{searchfield}` LIKE %(txt)s
prssannade7a2bc2020-09-21 13:57:04 +0530168 {mcond}
Suraj Shetty1923ef02020-08-05 19:42:25 +0530169 ORDER BY idx DESC, name
170 LIMIT %(offset)s, %(limit)s
prssannade7a2bc2020-09-21 13:57:04 +0530171 """.format(
172 account_type_condition=account_type_condition,
173 searchfield=searchfield,
174 mcond=get_match_cond(doctype)
175 ),
Suraj Shetty1923ef02020-08-05 19:42:25 +0530176 dict(
177 account_types=filters.get("account_type"),
178 company=filters.get("company"),
179 currency=company_currency,
180 txt="%{}%".format(txt),
181 offset=start,
182 limit=page_len
183 )
184 )
185
186 return accounts
187
188 tax_accounts = get_accounts(True)
189
Nabin Hait0c21e2a2014-03-21 11:14:49 +0530190 if not tax_accounts:
Suraj Shetty1923ef02020-08-05 19:42:25 +0530191 tax_accounts = get_accounts(False)
Anand Doshibd67e872014-04-11 16:51:27 +0530192
Nabin Hait0c21e2a2014-03-21 11:14:49 +0530193 return tax_accounts
Saurabh02875592013-07-08 18:45:55 +0530194
Himanshud94a38e2020-05-18 14:26:26 +0530195
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530196@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530197@frappe.validate_and_sanitize_search_inputs
Rushabh Mehta203cc962016-04-07 15:25:43 +0530198def item_query(doctype, txt, searchfield, start, page_len, filters, as_dict=False):
Saurabh02875592013-07-08 18:45:55 +0530199 conditions = []
Saurabhf52dc072013-07-10 13:07:49 +0530200
marination3dbef9d2019-10-28 15:48:10 +0530201 #Get searchfields from meta and use in Item Link field query
marination1e754b12019-10-30 18:33:44 +0530202 meta = frappe.get_meta("Item", cached=True)
marination3dbef9d2019-10-28 15:48:10 +0530203 searchfields = meta.get_search_fields()
204
marination1e754b12019-10-30 18:33:44 +0530205 if "description" in searchfields:
206 searchfields.remove("description")
marination3dbef9d2019-10-28 15:48:10 +0530207
Rohit Waghchaurec42312e2019-11-19 19:05:23 +0530208 columns = ''
209 extra_searchfields = [field for field in searchfields
210 if not field in ["name", "item_group", "description"]]
211
212 if extra_searchfields:
213 columns = ", " + ", ".join(extra_searchfields)
marination1e754b12019-10-30 18:33:44 +0530214
215 searchfields = searchfields + [field for field in[searchfield or "name", "item_code", "item_group", "item_name"]
216 if not field in searchfields]
marination3dbef9d2019-10-28 15:48:10 +0530217 searchfields = " or ".join([field + " like %(txt)s" for field in searchfields])
218
Rushabh Mehtad5f9ebd2018-04-02 23:37:33 +0530219 description_cond = ''
220 if frappe.db.count('Item', cache=True) < 50000:
221 # scan description only if items are less than 50000
222 description_cond = 'or tabItem.description LIKE %(txt)s'
223
Prateeksha Singh984a7a72018-05-17 17:29:36 +0530224 return frappe.db.sql("""select tabItem.name,
Anand Doshibd67e872014-04-11 16:51:27 +0530225 if(length(tabItem.item_name) > 40,
226 concat(substr(tabItem.item_name, 1, 40), "..."), item_name) as item_name,
Prateeksha Singh984a7a72018-05-17 17:29:36 +0530227 tabItem.item_group,
Saurabh02875592013-07-08 18:45:55 +0530228 if(length(tabItem.description) > 40, \
Rohit Waghchaurec42312e2019-11-19 19:05:23 +0530229 concat(substr(tabItem.description, 1, 40), "..."), description) as description
marination1e754b12019-10-30 18:33:44 +0530230 {columns}
Anand Doshibd67e872014-04-11 16:51:27 +0530231 from tabItem
Anand Doshi22c0d782013-11-04 16:23:04 +0530232 where tabItem.docstatus < 2
Anand Doshi21e09a22015-10-29 12:21:41 +0530233 and tabItem.disabled=0
rohitwaghchaure79789072020-05-21 18:10:13 +0530234 and tabItem.has_variants=0
Rushabh Mehta864d1ea2014-06-23 12:20:12 +0530235 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 +0530236 and ({scond} or tabItem.item_code IN (select parent from `tabItem Barcode` where barcode LIKE %(txt)s)
Rohit Waghchaure2bfb0632019-03-02 21:47:55 +0530237 {description_cond})
Anand Doshi22c0d782013-11-04 16:23:04 +0530238 {fcond} {mcond}
Anand Doshi652bc072014-04-16 15:21:46 +0530239 order by
240 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
241 if(locate(%(_txt)s, item_name), locate(%(_txt)s, item_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530242 idx desc,
Anand Doshi652bc072014-04-16 15:21:46 +0530243 name, item_name
Rushabh Mehtabc4e2cd2017-10-17 12:30:34 +0530244 limit %(start)s, %(page_len)s """.format(
marination1e754b12019-10-30 18:33:44 +0530245 columns=columns,
marination3dbef9d2019-10-28 15:48:10 +0530246 scond=searchfields,
Nabin Haitc6285062016-03-30 13:10:25 +0530247 fcond=get_filters_cond(doctype, filters, conditions).replace('%', '%%'),
Rushabh Mehtad5f9ebd2018-04-02 23:37:33 +0530248 mcond=get_match_cond(doctype).replace('%', '%%'),
249 description_cond = description_cond),
Anand Doshi22c0d782013-11-04 16:23:04 +0530250 {
251 "today": nowdate(),
252 "txt": "%%%s%%" % txt,
Anand Doshi652bc072014-04-16 15:21:46 +0530253 "_txt": txt.replace("%", ""),
Anand Doshi22c0d782013-11-04 16:23:04 +0530254 "start": start,
255 "page_len": page_len
Rushabh Mehta203cc962016-04-07 15:25:43 +0530256 }, as_dict=as_dict)
Saurabh02875592013-07-08 18:45:55 +0530257
Himanshud94a38e2020-05-18 14:26:26 +0530258
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530259@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530260@frappe.validate_and_sanitize_search_inputs
Saurabh022ab632017-11-10 15:06:02 +0530261def bom(doctype, txt, searchfield, start, page_len, filters):
Anand Doshibd67e872014-04-11 16:51:27 +0530262 conditions = []
Himanshud94a38e2020-05-18 14:26:26 +0530263 fields = get_fields("BOM", ["name", "item"])
Saurabhf52dc072013-07-10 13:07:49 +0530264
Himanshud94a38e2020-05-18 14:26:26 +0530265 return frappe.db.sql("""select {fields}
Anand Doshibd67e872014-04-11 16:51:27 +0530266 from tabBOM
267 where tabBOM.docstatus=1
268 and tabBOM.is_active=1
Nabin Hait62211172016-03-16 16:22:03 +0530269 and tabBOM.`{key}` like %(txt)s
270 {fcond} {mcond}
271 order by
Rushabh Mehta3574b372016-03-11 14:33:04 +0530272 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
273 idx desc, name
Nabin Hait62211172016-03-16 16:22:03 +0530274 limit %(start)s, %(page_len)s """.format(
Himanshud94a38e2020-05-18 14:26:26 +0530275 fields=", ".join(fields),
Mangesh-Khairnar6a796912019-07-08 10:40:40 +0530276 fcond=get_filters_cond(doctype, filters, conditions).replace('%', '%%'),
Karthikeyan S747c2622019-07-19 22:49:21 +0530277 mcond=get_match_cond(doctype).replace('%', '%%'),
278 key=searchfield),
Mangesh-Khairnar6a796912019-07-08 10:40:40 +0530279 {
Karthikeyan S747c2622019-07-19 22:49:21 +0530280 'txt': '%' + txt + '%',
Rushabh Mehta3574b372016-03-11 14:33:04 +0530281 '_txt': txt.replace("%", ""),
Saurabh022ab632017-11-10 15:06:02 +0530282 'start': start or 0,
283 'page_len': page_len or 20
Rushabh Mehta3574b372016-03-11 14:33:04 +0530284 })
Saurabh02875592013-07-08 18:45:55 +0530285
Himanshud94a38e2020-05-18 14:26:26 +0530286
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530287@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530288@frappe.validate_and_sanitize_search_inputs
Saurabh02875592013-07-08 18:45:55 +0530289def get_project_name(doctype, txt, searchfield, start, page_len, filters):
290 cond = ''
Nabin Haitf71011a2014-08-21 11:34:31 +0530291 if filters.get('customer'):
Suraj Shetty6ea3de92018-09-26 18:15:53 +0530292 cond = """(`tabProject`.customer = %s or
rohitwaghchauree3304722018-08-27 11:43:57 +0530293 ifnull(`tabProject`.customer,"")="") and""" %(frappe.db.escape(filters.get("customer")))
Anand Doshibd67e872014-04-11 16:51:27 +0530294
Rucha Mahabal062d3012021-05-07 13:31:14 +0530295 fields = get_fields("Project", ["name", "project_name"])
296 searchfields = frappe.get_meta("Project").get_search_fields()
297 searchfields = " or ".join([field + " like %(txt)s" for field in searchfields])
Himanshud94a38e2020-05-18 14:26:26 +0530298
299 return frappe.db.sql("""select {fields} from `tabProject`
Rucha Mahabal062d3012021-05-07 13:31:14 +0530300 where
301 `tabProject`.status not in ("Completed", "Cancelled")
302 and {cond} {match_cond} {scond}
Rushabh Mehta3574b372016-03-11 14:33:04 +0530303 order by
304 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
305 idx desc,
306 `tabProject`.name asc
307 limit {start}, {page_len}""".format(
Himanshud94a38e2020-05-18 14:26:26 +0530308 fields=", ".join(['`tabProject`.{0}'.format(f) for f in fields]),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530309 cond=cond,
Rucha Mahabal062d3012021-05-07 13:31:14 +0530310 scond=searchfields,
Rushabh Mehta3574b372016-03-11 14:33:04 +0530311 match_cond=get_match_cond(doctype),
312 start=start,
313 page_len=page_len), {
314 "txt": "%{0}%".format(txt),
Nabin Haitdf4deba2016-03-16 11:16:31 +0530315 "_txt": txt.replace('%', '')
Rushabh Mehta3574b372016-03-11 14:33:04 +0530316 })
Anand Doshibd67e872014-04-11 16:51:27 +0530317
tundebabzyf6d738b2017-09-18 12:40:09 +0100318
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530319@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530320@frappe.validate_and_sanitize_search_inputs
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530321def get_delivery_notes_to_be_billed(doctype, txt, searchfield, start, page_len, filters, as_dict):
Himanshud94a38e2020-05-18 14:26:26 +0530322 fields = get_fields("Delivery Note", ["name", "customer", "posting_date"])
323
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530324 return frappe.db.sql("""
Himanshud94a38e2020-05-18 14:26:26 +0530325 select %(fields)s
Anand Doshibd67e872014-04-11 16:51:27 +0530326 from `tabDelivery Note`
327 where `tabDelivery Note`.`%(key)s` like %(txt)s and
tundebabzyf6d738b2017-09-18 12:40:09 +0100328 `tabDelivery Note`.docstatus = 1
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530329 and status not in ("Stopped", "Closed") %(fcond)s
tundebabzyf6d738b2017-09-18 12:40:09 +0100330 and (
331 (`tabDelivery Note`.is_return = 0 and `tabDelivery Note`.per_billed < 100)
Deepesh Garge2dc1022021-04-14 11:21:11 +0530332 or (`tabDelivery Note`.grand_total = 0 and `tabDelivery Note`.per_billed < 100)
tundebabzyf6d738b2017-09-18 12:40:09 +0100333 or (
334 `tabDelivery Note`.is_return = 1
335 and return_against in (select name from `tabDelivery Note` where per_billed < 100)
336 )
337 )
rohitwaghchaured07a3e12019-05-15 07:46:28 +0530338 %(mcond)s order by `tabDelivery Note`.`%(key)s` asc limit %(start)s, %(page_len)s
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530339 """ % {
Himanshud94a38e2020-05-18 14:26:26 +0530340 "fields": ", ".join(["`tabDelivery Note`.{0}".format(f) for f in fields]),
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530341 "key": searchfield,
342 "fcond": get_filters_cond(doctype, filters, []),
343 "mcond": get_match_cond(doctype),
rohitwaghchaured07a3e12019-05-15 07:46:28 +0530344 "start": start,
345 "page_len": page_len,
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530346 "txt": "%(txt)s"
tundebabzyf6d738b2017-09-18 12:40:09 +0100347 }, {"txt": ("%%%s%%" % txt)}, as_dict=as_dict)
348
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530349
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530350@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530351@frappe.validate_and_sanitize_search_inputs
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530352def get_batch_no(doctype, txt, searchfield, start, page_len, filters):
Neil Trini Lasradoebb60f52015-07-08 14:36:09 +0530353 cond = ""
354 if filters.get("posting_date"):
Nabin Hait7918b922018-01-31 15:30:03 +0530355 cond = "and (batch.expiry_date is null or batch.expiry_date >= %(posting_date)s)"
Rushabh Mehtab6398be2015-08-26 10:50:16 +0530356
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530357 batch_nos = None
358 args = {
359 'item_code': filters.get("item_code"),
360 'warehouse': filters.get("warehouse"),
361 'posting_date': filters.get('posting_date'),
Anand Doshi0dc79f42015-04-06 12:59:34 +0530362 'txt': "%{0}%".format(txt),
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530363 "start": start,
364 "page_len": page_len
365 }
366
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530367 having_clause = "having sum(sle.actual_qty) > 0"
368 if filters.get("is_return"):
369 having_clause = ""
370
Deepesh Garga0d192e2020-09-22 13:54:07 +0530371 meta = frappe.get_meta("Batch", cached=True)
372 searchfields = meta.get_search_fields()
373
374 search_columns = ''
Deepesh Gargf58a5ec2020-10-05 13:55:53 +0530375 search_cond = ''
376
Deepesh Garga0d192e2020-09-22 13:54:07 +0530377 if searchfields:
378 search_columns = ", " + ", ".join(searchfields)
Deepesh Garg1fae7742020-10-05 12:38:54 +0530379 search_cond = " or " + " or ".join([field + " like %(txt)s" for field in searchfields])
Deepesh Garga0d192e2020-09-22 13:54:07 +0530380
Anand Doshi0dc79f42015-04-06 12:59:34 +0530381 if args.get('warehouse'):
Deepesh Garga0d192e2020-09-22 13:54:07 +0530382 searchfields = ['batch.' + field for field in searchfields]
383 if searchfields:
384 search_columns = ", " + ", ".join(searchfields)
Deepesh Garg1fae7742020-10-05 12:38:54 +0530385 search_cond = " or " + " or ".join([field + " like %(txt)s" for field in searchfields])
Deepesh Garga0d192e2020-09-22 13:54:07 +0530386
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530387 batch_nos = frappe.db.sql("""select sle.batch_no, round(sum(sle.actual_qty),2), sle.stock_uom,
388 concat('MFG-',batch.manufacturing_date), concat('EXP-',batch.expiry_date)
Deepesh Garga0d192e2020-09-22 13:54:07 +0530389 {search_columns}
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530390 from `tabStock Ledger Entry` sle
391 INNER JOIN `tabBatch` batch on sle.batch_no = batch.name
392 where
393 batch.disabled = 0
394 and sle.item_code = %(item_code)s
395 and sle.warehouse = %(warehouse)s
396 and (sle.batch_no like %(txt)s
Sun Howwrongbum088be372019-12-24 12:29:25 +0530397 or batch.expiry_date like %(txt)s
Deepesh Gargf58a5ec2020-10-05 13:55:53 +0530398 or batch.manufacturing_date like %(txt)s
399 {search_cond})
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530400 and batch.docstatus < 2
401 {cond}
402 {match_conditions}
403 group by batch_no {having_clause}
404 order by batch.expiry_date, sle.batch_no desc
405 limit %(start)s, %(page_len)s""".format(
Deepesh Garga0d192e2020-09-22 13:54:07 +0530406 search_columns = search_columns,
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530407 cond=cond,
408 match_conditions=get_match_cond(doctype),
Deepesh Garg1fae7742020-10-05 12:38:54 +0530409 having_clause = having_clause,
410 search_cond = search_cond
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530411 ), args)
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530412
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530413 return batch_nos
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530414 else:
Deepesh Garga0d192e2020-09-22 13:54:07 +0530415 return frappe.db.sql("""select name, concat('MFG-', manufacturing_date), concat('EXP-',expiry_date)
416 {search_columns}
417 from `tabBatch` batch
Doridel Cahanap59e4c322018-08-06 17:15:18 +0800418 where batch.disabled = 0
419 and item = %(item_code)s
sivankar621740e2018-02-12 14:33:40 +0530420 and (name like %(txt)s
Sun Howwrongbum088be372019-12-24 12:29:25 +0530421 or expiry_date like %(txt)s
Deepesh Gargf58a5ec2020-10-05 13:55:53 +0530422 or manufacturing_date like %(txt)s
423 {search_cond})
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530424 and docstatus < 2
Neil Trini Lasradoebb60f52015-07-08 14:36:09 +0530425 {0}
Anand Doshi0dc79f42015-04-06 12:59:34 +0530426 {match_conditions}
Deepesh Gargf58a5ec2020-10-05 13:55:53 +0530427
Anand Doshi0dc79f42015-04-06 12:59:34 +0530428 order by expiry_date, name desc
Deepesh Garg1fae7742020-10-05 12:38:54 +0530429 limit %(start)s, %(page_len)s""".format(cond, search_columns = search_columns,
430 search_cond = search_cond, match_conditions=get_match_cond(doctype)), args)
Nabin Haitea4aa042014-05-28 12:56:28 +0530431
Himanshud94a38e2020-05-18 14:26:26 +0530432
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530433@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530434@frappe.validate_and_sanitize_search_inputs
Nabin Haitea4aa042014-05-28 12:56:28 +0530435def get_account_list(doctype, txt, searchfield, start, page_len, filters):
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530436 filter_list = []
Nabin Haitea4aa042014-05-28 12:56:28 +0530437
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530438 if isinstance(filters, dict):
439 for key, val in filters.items():
440 if isinstance(val, (list, tuple)):
441 filter_list.append([doctype, key, val[0], val[1]])
442 else:
443 filter_list.append([doctype, key, "=", val])
bhupeshg2e2e973f2015-04-14 22:15:24 +0530444 elif isinstance(filters, list):
445 filter_list.extend(filters)
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530446
Rushabh Mehta38c6b522015-04-23 13:14:17 +0530447 if "is_group" not in [d[1] for d in filter_list]:
448 filter_list.append(["Account", "is_group", "=", "0"])
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530449
450 if searchfield and txt:
451 filter_list.append([doctype, searchfield, "like", "%%%s%%" % txt])
452
Rushabh Mehtac0bb4532014-09-09 16:15:35 +0530453 return frappe.desk.reportview.execute("Account", filters = filter_list,
Nabin Haitea4aa042014-05-28 12:56:28 +0530454 fields = ["name", "parent_account"],
455 limit_start=start, limit_page_length=page_len, as_list=True)
Anand Doshifaefeaa2014-06-24 18:53:04 +0530456
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530457@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530458@frappe.validate_and_sanitize_search_inputs
Marica299e2172020-04-28 13:00:04 +0530459def get_blanket_orders(doctype, txt, searchfield, start, page_len, filters):
460 return frappe.db.sql("""select distinct bo.name, bo.blanket_order_type, bo.to_date
461 from `tabBlanket Order` bo, `tabBlanket Order Item` boi
462 where
463 boi.parent = bo.name
464 and boi.item_code = {item_code}
465 and bo.blanket_order_type = '{blanket_order_type}'
466 and bo.company = {company}
467 and bo.docstatus = 1"""
468 .format(item_code = frappe.db.escape(filters.get("item")),
469 blanket_order_type = filters.get("blanket_order_type"),
470 company = frappe.db.escape(filters.get("company"))
471 ))
Nabin Haitafd14f62015-10-19 11:55:28 +0530472
Himanshud94a38e2020-05-18 14:26:26 +0530473
Nabin Haitafd14f62015-10-19 11:55:28 +0530474@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530475@frappe.validate_and_sanitize_search_inputs
Nabin Haitafd14f62015-10-19 11:55:28 +0530476def get_income_account(doctype, txt, searchfield, start, page_len, filters):
477 from erpnext.controllers.queries import get_match_cond
478
479 # income account can be any Credit account,
480 # but can also be a Asset account with account_type='Income Account' in special circumstances.
481 # Hence the first condition is an "OR"
482 if not filters: filters = {}
483
Anand Doshi21e09a22015-10-29 12:21:41 +0530484 condition = ""
Nabin Haitafd14f62015-10-19 11:55:28 +0530485 if filters.get("company"):
486 condition += "and tabAccount.company = %(company)s"
Anand Doshi21e09a22015-10-29 12:21:41 +0530487
Nabin Haitafd14f62015-10-19 11:55:28 +0530488 return frappe.db.sql("""select tabAccount.name from `tabAccount`
489 where (tabAccount.report_type = "Profit and Loss"
490 or tabAccount.account_type in ("Income Account", "Temporary"))
491 and tabAccount.is_group=0
492 and tabAccount.`{key}` LIKE %(txt)s
Rushabh Mehta3574b372016-03-11 14:33:04 +0530493 {condition} {match_condition}
494 order by idx desc, name"""
Nabin Haitafd14f62015-10-19 11:55:28 +0530495 .format(condition=condition, match_condition=get_match_cond(doctype), key=searchfield), {
Suraj Shetty4b404c42018-09-27 15:39:34 +0530496 'txt': '%' + txt + '%',
Nabin Haitafd14f62015-10-19 11:55:28 +0530497 'company': filters.get("company", "")
Anand Doshi21e09a22015-10-29 12:21:41 +0530498 })
Nabin Hait3a15c922016-03-04 12:30:46 +0530499
Deepesh Garg96e874b2020-11-15 22:43:01 +0530500@frappe.whitelist()
501@frappe.validate_and_sanitize_search_inputs
502def get_filtered_dimensions(doctype, txt, searchfield, start, page_len, filters):
503 from erpnext.accounts.doctype.accounting_dimension_filter.accounting_dimension_filter import get_dimension_filter_map
504 dimension_filters = get_dimension_filter_map()
505 dimension_filters = dimension_filters.get((filters.get('dimension'),filters.get('account')))
Deepesh Garg6c17b842020-11-25 13:42:16 +0530506 query_filters = []
Deepesh Garg96e874b2020-11-15 22:43:01 +0530507
508 meta = frappe.get_meta(doctype)
Deepesh Garg96e874b2020-11-15 22:43:01 +0530509 if meta.is_tree:
Deepesh Garg6c17b842020-11-25 13:42:16 +0530510 query_filters.append(['is_group', '=', 0])
Deepesh Garg96e874b2020-11-15 22:43:01 +0530511
512 if meta.has_field('company'):
Deepesh Garg6c17b842020-11-25 13:42:16 +0530513 query_filters.append(['company', '=', filters.get('company')])
514
515 if txt:
516 query_filters.append([searchfield, 'LIKE', "%%%s%%" % txt])
Deepesh Garg96e874b2020-11-15 22:43:01 +0530517
518 if dimension_filters:
519 if dimension_filters['allow_or_restrict'] == 'Allow':
520 query_selector = 'in'
521 else:
522 query_selector = 'not in'
523
524 if len(dimension_filters['allowed_dimensions']) == 1:
525 dimensions = tuple(dimension_filters['allowed_dimensions'] * 2)
526 else:
527 dimensions = tuple(dimension_filters['allowed_dimensions'])
528
Deepesh Garg6c17b842020-11-25 13:42:16 +0530529 query_filters.append(['name', query_selector, dimensions])
Deepesh Garg96e874b2020-11-15 22:43:01 +0530530
Deepesh Garg6c17b842020-11-25 13:42:16 +0530531 output = frappe.get_all(doctype, filters=query_filters)
532 result = [d.name for d in output]
533
534 return [(d,) for d in set(result)]
Nabin Hait3a15c922016-03-04 12:30:46 +0530535
536@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530537@frappe.validate_and_sanitize_search_inputs
Nabin Hait3a15c922016-03-04 12:30:46 +0530538def get_expense_account(doctype, txt, searchfield, start, page_len, filters):
539 from erpnext.controllers.queries import get_match_cond
Rushabh Mehta203cc962016-04-07 15:25:43 +0530540
Nabin Hait3a15c922016-03-04 12:30:46 +0530541 if not filters: filters = {}
542
543 condition = ""
544 if filters.get("company"):
545 condition += "and tabAccount.company = %(company)s"
Rushabh Mehta203cc962016-04-07 15:25:43 +0530546
Nabin Hait3a15c922016-03-04 12:30:46 +0530547 return frappe.db.sql("""select tabAccount.name from `tabAccount`
548 where (tabAccount.report_type = "Profit and Loss"
Mangesh-Khairnar5619db22019-08-21 14:49:24 +0530549 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 +0530550 and tabAccount.is_group=0
551 and tabAccount.docstatus!=2
552 and tabAccount.{key} LIKE %(txt)s
553 {condition} {match_condition}"""
Suraj Shettybfc195d2018-09-21 10:20:52 +0530554 .format(condition=condition, key=searchfield,
Nabin Hait3a15c922016-03-04 12:30:46 +0530555 match_condition=get_match_cond(doctype)), {
Neil Trini Lasrado30b97b02016-03-31 23:10:13 +0530556 'company': filters.get("company", ""),
Suraj Shetty4b404c42018-09-27 15:39:34 +0530557 'txt': '%' + txt + '%'
Maxwell Morais35572612016-07-21 23:42:59 -0300558 })
suyashphadtare049a88c2017-01-12 17:49:37 +0530559
560
561@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530562@frappe.validate_and_sanitize_search_inputs
suyashphadtare049a88c2017-01-12 17:49:37 +0530563def warehouse_query(doctype, txt, searchfield, start, page_len, filters):
564 # Should be used when item code is passed in filters.
suyashphadtare750a0672017-01-18 15:35:01 +0530565 conditions, bin_conditions = [], []
566 filter_dict = get_doctype_wise_filters(filters)
567
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530568 query = """select `tabWarehouse`.name,
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530569 CONCAT_WS(" : ", "Actual Qty", ifnull(round(`tabBin`.actual_qty, 2), 0 )) actual_qty
570 from `tabWarehouse` left join `tabBin`
571 on `tabBin`.warehouse = `tabWarehouse`.name {bin_conditions}
suyashphadtare34ab1362017-01-31 15:14:44 +0530572 where
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530573 `tabWarehouse`.`{key}` like {txt}
suyashphadtare34ab1362017-01-31 15:14:44 +0530574 {fcond} {mcond}
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530575 order by ifnull(`tabBin`.actual_qty, 0) desc
suyashphadtare34ab1362017-01-31 15:14:44 +0530576 limit
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530577 {start}, {page_len}
suyashphadtare34ab1362017-01-31 15:14:44 +0530578 """.format(
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530579 bin_conditions=get_filters_cond(doctype, filter_dict.get("Bin"),bin_conditions, ignore_permissions=True),
Suraj Shettybfc195d2018-09-21 10:20:52 +0530580 key=searchfield,
suyashphadtare34ab1362017-01-31 15:14:44 +0530581 fcond=get_filters_cond(doctype, filter_dict.get("Warehouse"), conditions),
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530582 mcond=get_match_cond(doctype),
583 start=start,
584 page_len=page_len,
585 txt=frappe.db.escape('%{0}%'.format(txt))
586 )
587
588 return frappe.db.sql(query)
suyashphadtare750a0672017-01-18 15:35:01 +0530589
590
591def get_doctype_wise_filters(filters):
592 # Helper function to seperate filters doctype_wise
593 filter_dict = defaultdict(list)
594 for row in filters:
595 filter_dict[row[0]].append(row)
596 return filter_dict
tundebabzy2a4fefc2017-11-29 06:23:09 +0100597
598
599@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530600@frappe.validate_and_sanitize_search_inputs
tundebabzy2a4fefc2017-11-29 06:23:09 +0100601def get_batch_numbers(doctype, txt, searchfield, start, page_len, filters):
rohitwaghchaure9fbed562018-01-12 16:22:33 +0530602 query = """select batch_id from `tabBatch`
Doridel Cahanap59e4c322018-08-06 17:15:18 +0800603 where disabled = 0
604 and (expiry_date >= CURDATE() or expiry_date IS NULL)
Suraj Shettybfc195d2018-09-21 10:20:52 +0530605 and name like {txt}""".format(txt = frappe.db.escape('%{0}%'.format(txt)))
tundebabzy2a4fefc2017-11-29 06:23:09 +0100606
rohitwaghchaure9fbed562018-01-12 16:22:33 +0530607 if filters and filters.get('item'):
Suraj Shettybfc195d2018-09-21 10:20:52 +0530608 query += " and item = {item}".format(item = frappe.db.escape(filters.get('item')))
tundebabzy2a4fefc2017-11-29 06:23:09 +0100609
Sachin Mane64f48db2018-01-08 17:57:32 +0530610 return frappe.db.sql(query, filters)
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530611
Himanshud94a38e2020-05-18 14:26:26 +0530612
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530613@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530614@frappe.validate_and_sanitize_search_inputs
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530615def item_manufacturer_query(doctype, txt, searchfield, start, page_len, filters):
Maricabac4b932019-09-16 19:44:28 +0530616 item_filters = [
617 ['manufacturer', 'like', '%' + txt + '%'],
618 ['item_code', '=', filters.get("item_code")]
619 ]
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530620
Maricabac4b932019-09-16 19:44:28 +0530621 item_manufacturers = frappe.get_all(
622 "Item Manufacturer",
623 fields=["manufacturer", "manufacturer_part_no"],
624 filters=item_filters,
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530625 limit_start=start,
626 limit_page_length=page_len,
627 as_list=1
628 )
Maricabac4b932019-09-16 19:44:28 +0530629 return item_manufacturers
Saqibd9956092019-11-18 11:46:55 +0530630
Himanshud94a38e2020-05-18 14:26:26 +0530631
Saqibd9956092019-11-18 11:46:55 +0530632@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530633@frappe.validate_and_sanitize_search_inputs
Saqibd9956092019-11-18 11:46:55 +0530634def get_purchase_receipts(doctype, txt, searchfield, start, page_len, filters):
635 query = """
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530636 select pr.name
Saqibd9956092019-11-18 11:46:55 +0530637 from `tabPurchase Receipt` pr, `tabPurchase Receipt Item` pritem
638 where pr.docstatus = 1 and pritem.parent = pr.name
639 and pr.name like {txt}""".format(txt = frappe.db.escape('%{0}%'.format(txt)))
640
641 if filters and filters.get('item_code'):
642 query += " and pritem.item_code = {item_code}".format(item_code = frappe.db.escape(filters.get('item_code')))
643
644 return frappe.db.sql(query, filters)
645
Himanshud94a38e2020-05-18 14:26:26 +0530646
Saqibd9956092019-11-18 11:46:55 +0530647@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530648@frappe.validate_and_sanitize_search_inputs
Saqibd9956092019-11-18 11:46:55 +0530649def get_purchase_invoices(doctype, txt, searchfield, start, page_len, filters):
650 query = """
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530651 select pi.name
Saqibd9956092019-11-18 11:46:55 +0530652 from `tabPurchase Invoice` pi, `tabPurchase Invoice Item` piitem
653 where pi.docstatus = 1 and piitem.parent = pi.name
654 and pi.name like {txt}""".format(txt = frappe.db.escape('%{0}%'.format(txt)))
655
656 if filters and filters.get('item_code'):
657 query += " and piitem.item_code = {item_code}".format(item_code = frappe.db.escape(filters.get('item_code')))
658
659 return frappe.db.sql(query, filters)
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530660
Himanshud94a38e2020-05-18 14:26:26 +0530661
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530662@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530663@frappe.validate_and_sanitize_search_inputs
Rucha Mahabal20e53152021-01-18 14:56:55 +0530664def get_healthcare_service_units(doctype, txt, searchfield, start, page_len, filters):
665 query = """
666 select name
667 from `tabHealthcare Service Unit`
668 where
669 is_group = 0
670 and company = {company}
671 and name like {txt}""".format(
672 company = frappe.db.escape(filters.get('company')), txt = frappe.db.escape('%{0}%'.format(txt)))
673
674 if filters and filters.get('inpatient_record'):
675 from erpnext.healthcare.doctype.inpatient_medication_entry.inpatient_medication_entry import get_current_healthcare_service_unit
676 service_unit = get_current_healthcare_service_unit(filters.get('inpatient_record'))
677
678 # if the patient is admitted, then appointments should be allowed against the admission service unit,
679 # inspite of it being an Inpatient Occupancy service unit
680 if service_unit:
681 query += " and (allow_appointments = 1 or name = {service_unit})".format(service_unit = frappe.db.escape(service_unit))
682 else:
683 query += " and allow_appointments = 1"
684 else:
685 query += " and allow_appointments = 1"
686
687 return frappe.db.sql(query, filters)
688
689
690@frappe.whitelist()
691@frappe.validate_and_sanitize_search_inputs
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530692def get_tax_template(doctype, txt, searchfield, start, page_len, filters):
693
694 item_doc = frappe.get_cached_doc('Item', filters.get('item_code'))
695 item_group = filters.get('item_group')
696 taxes = item_doc.taxes or []
697
698 while item_group:
699 item_group_doc = frappe.get_cached_doc('Item Group', item_group)
700 taxes += item_group_doc.taxes or []
701 item_group = item_group_doc.parent_item_group
702
703 if not taxes:
704 return frappe.db.sql(""" SELECT name FROM `tabItem Tax Template` """)
705 else:
Marica0fcb05a2020-08-10 14:48:13 +0530706 valid_from = filters.get('valid_from')
707 valid_from = valid_from[1] if isinstance(valid_from, list) else valid_from
708
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530709 args = {
710 'item_code': filters.get('item_code'),
Marica0fcb05a2020-08-10 14:48:13 +0530711 'posting_date': valid_from,
mohammadahmad199041c0c9f2020-06-18 11:18:44 +0500712 'tax_category': filters.get('tax_category'),
713 'company': filters.get('company')
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530714 }
715
716 taxes = _get_item_tax_template(args, taxes, for_validate=True)
717 return [(d,) for d in set(taxes)]
Himanshud94a38e2020-05-18 14:26:26 +0530718
719
Ankush Menat7eac4a22021-04-19 10:33:39 +0530720def get_fields(doctype, fields=None):
721 if fields is None:
722 fields = []
Himanshud94a38e2020-05-18 14:26:26 +0530723 meta = frappe.get_meta(doctype)
724 fields.extend(meta.get_search_fields())
725
726 if meta.title_field and not meta.title_field.strip() in fields:
727 fields.insert(1, meta.title_field.strip())
728
729 return unique(fields)