blob: aafaf5b9e083deee567282380d34ceebb42ef61f [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
Chillar Anand915b3432021-09-02 16:44:59 +05305
rohitwaghchaurec59371a2021-06-03 20:02:58 +05306import json
suyashphadtare750a0672017-01-18 15:35:01 +05307from collections import defaultdict
Chillar Anand915b3432021-09-02 16:44:59 +05308
9import frappe
10from frappe.desk.reportview import get_filters_cond, get_match_cond
11from frappe.utils import nowdate, unique
12
13import erpnext
Deepesh Gargef0d26c2020-01-06 15:34:15 +053014from erpnext.stock.get_item_details import _get_item_tax_template
Chillar Anand915b3432021-09-02 16:44:59 +053015
Saurabh02875592013-07-08 18:45:55 +053016
Chinmay D. Paiaa121092020-07-01 21:14:32 +053017# searches for active employees
18@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +053019@frappe.validate_and_sanitize_search_inputs
Saurabh02875592013-07-08 18:45:55 +053020def employee_query(doctype, txt, searchfield, start, page_len, filters):
Kanchan Chauhan7652b852016-11-16 15:29:01 +053021 conditions = []
Himanshud94a38e2020-05-18 14:26:26 +053022 fields = get_fields("Employee", ["name", "employee_name"])
23
24 return frappe.db.sql("""select {fields} from `tabEmployee`
Anurag Mishrafc98abe2021-06-23 11:21:38 +053025 where status in ('Active', 'Suspended')
Anand Doshibd67e872014-04-11 16:51:27 +053026 and docstatus < 2
Anand Doshi48d3b542014-07-09 13:15:03 +053027 and ({key} like %(txt)s
28 or employee_name like %(txt)s)
Kanchan Chauhan7652b852016-11-16 15:29:01 +053029 {fcond} {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +053030 order by
Anand Doshi48d3b542014-07-09 13:15:03 +053031 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
32 if(locate(%(_txt)s, employee_name), locate(%(_txt)s, employee_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +053033 idx desc,
Anand Doshi652bc072014-04-16 15:21:46 +053034 name, employee_name
Anand Doshi48d3b542014-07-09 13:15:03 +053035 limit %(start)s, %(page_len)s""".format(**{
Himanshud94a38e2020-05-18 14:26:26 +053036 'fields': ", ".join(fields),
Anand Doshi48d3b542014-07-09 13:15:03 +053037 'key': searchfield,
Kanchan Chauhan7652b852016-11-16 15:29:01 +053038 'fcond': get_filters_cond(doctype, filters, conditions),
Anand Doshi48d3b542014-07-09 13:15:03 +053039 'mcond': get_match_cond(doctype)
40 }), {
41 'txt': "%%%s%%" % txt,
42 '_txt': txt.replace("%", ""),
43 'start': start,
44 'page_len': page_len
45 })
Saurabh02875592013-07-08 18:45:55 +053046
Himanshud94a38e2020-05-18 14:26:26 +053047
48# searches for leads which are not converted
Chinmay D. Paiaa121092020-07-01 21:14:32 +053049@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +053050@frappe.validate_and_sanitize_search_inputs
Anand Doshibd67e872014-04-11 16:51:27 +053051def lead_query(doctype, txt, searchfield, start, page_len, filters):
Himanshud94a38e2020-05-18 14:26:26 +053052 fields = get_fields("Lead", ["name", "lead_name", "company_name"])
53
54 return frappe.db.sql("""select {fields} from `tabLead`
Anand Doshibd67e872014-04-11 16:51:27 +053055 where docstatus < 2
56 and ifnull(status, '') != 'Converted'
Anand Doshi48d3b542014-07-09 13:15:03 +053057 and ({key} like %(txt)s
58 or lead_name like %(txt)s
59 or company_name like %(txt)s)
60 {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +053061 order by
Anand Doshi48d3b542014-07-09 13:15:03 +053062 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
63 if(locate(%(_txt)s, lead_name), locate(%(_txt)s, lead_name), 99999),
64 if(locate(%(_txt)s, company_name), locate(%(_txt)s, company_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +053065 idx desc,
Anand Doshi652bc072014-04-16 15:21:46 +053066 name, lead_name
Anand Doshi48d3b542014-07-09 13:15:03 +053067 limit %(start)s, %(page_len)s""".format(**{
Himanshud94a38e2020-05-18 14:26:26 +053068 'fields': ", ".join(fields),
Anand Doshi48d3b542014-07-09 13:15:03 +053069 'key': searchfield,
70 'mcond':get_match_cond(doctype)
71 }), {
72 'txt': "%%%s%%" % txt,
73 '_txt': txt.replace("%", ""),
74 'start': start,
75 'page_len': page_len
76 })
Saurabh02875592013-07-08 18:45:55 +053077
Himanshud94a38e2020-05-18 14:26:26 +053078
Saurabh02875592013-07-08 18:45:55 +053079 # searches for customer
Chinmay D. Paiaa121092020-07-01 21:14:32 +053080@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +053081@frappe.validate_and_sanitize_search_inputs
Saurabh02875592013-07-08 18:45:55 +053082def customer_query(doctype, txt, searchfield, start, page_len, filters):
KanchanChauhan4b888b92017-07-25 14:03:01 +053083 conditions = []
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053084 cust_master_name = frappe.defaults.get_user_default("cust_master_name")
Saurabhf52dc072013-07-10 13:07:49 +053085
Saurabh02875592013-07-08 18:45:55 +053086 if cust_master_name == "Customer Name":
87 fields = ["name", "customer_group", "territory"]
88 else:
89 fields = ["name", "customer_name", "customer_group", "territory"]
Rushabh Mehtab92087c2017-01-13 18:53:11 +053090
Himanshud94a38e2020-05-18 14:26:26 +053091 fields = get_fields("Customer", fields)
Saurabhf52dc072013-07-10 13:07:49 +053092
Himanshud94a38e2020-05-18 14:26:26 +053093 searchfields = frappe.get_meta("Customer").get_search_fields()
Ankush Menata9c84f72021-06-11 16:00:48 +053094 searchfields = " or ".join(field + " like %(txt)s" for field in searchfields)
Saurabh02875592013-07-08 18:45:55 +053095
Anand Doshi48d3b542014-07-09 13:15:03 +053096 return frappe.db.sql("""select {fields} from `tabCustomer`
Anand Doshibd67e872014-04-11 16:51:27 +053097 where docstatus < 2
Console Admin86231662017-06-23 20:32:52 +030098 and ({scond}) and disabled=0
KanchanChauhan4b888b92017-07-25 14:03:01 +053099 {fcond} {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +0530100 order by
Anand Doshi48d3b542014-07-09 13:15:03 +0530101 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
102 if(locate(%(_txt)s, customer_name), locate(%(_txt)s, customer_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530103 idx desc,
Anand Doshibd67e872014-04-11 16:51:27 +0530104 name, customer_name
Anand Doshi48d3b542014-07-09 13:15:03 +0530105 limit %(start)s, %(page_len)s""".format(**{
Himanshud94a38e2020-05-18 14:26:26 +0530106 "fields": ", ".join(fields),
Console Admin86231662017-06-23 20:32:52 +0300107 "scond": searchfields,
KanchanChauhan4b888b92017-07-25 14:03:01 +0530108 "mcond": get_match_cond(doctype),
109 "fcond": get_filters_cond(doctype, filters, conditions).replace('%', '%%'),
Anand Doshi48d3b542014-07-09 13:15:03 +0530110 }), {
111 'txt': "%%%s%%" % txt,
112 '_txt': txt.replace("%", ""),
113 'start': start,
114 'page_len': page_len
115 })
Saurabh02875592013-07-08 18:45:55 +0530116
Himanshud94a38e2020-05-18 14:26:26 +0530117
Saurabh02875592013-07-08 18:45:55 +0530118# searches for supplier
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530119@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530120@frappe.validate_and_sanitize_search_inputs
Saurabh02875592013-07-08 18:45:55 +0530121def supplier_query(doctype, txt, searchfield, start, page_len, filters):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530122 supp_master_name = frappe.defaults.get_user_default("supp_master_name")
Suraj Shetty1923ef02020-08-05 19:42:25 +0530123
Anand Doshibd67e872014-04-11 16:51:27 +0530124 if supp_master_name == "Supplier Name":
Zlash652e080982018-04-19 18:37:53 +0530125 fields = ["name", "supplier_group"]
Anand Doshibd67e872014-04-11 16:51:27 +0530126 else:
Zlash652e080982018-04-19 18:37:53 +0530127 fields = ["name", "supplier_name", "supplier_group"]
Himanshud94a38e2020-05-18 14:26:26 +0530128
129 fields = get_fields("Supplier", fields)
Saurabh02875592013-07-08 18:45:55 +0530130
Anand Doshi48d3b542014-07-09 13:15:03 +0530131 return frappe.db.sql("""select {field} from `tabSupplier`
Anand Doshibd67e872014-04-11 16:51:27 +0530132 where docstatus < 2
Anand Doshi48d3b542014-07-09 13:15:03 +0530133 and ({key} like %(txt)s
shreyas29b565f2016-01-25 17:30:49 +0530134 or supplier_name like %(txt)s) and disabled=0
Anand Doshi48d3b542014-07-09 13:15:03 +0530135 {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +0530136 order by
Anand Doshi48d3b542014-07-09 13:15:03 +0530137 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
138 if(locate(%(_txt)s, supplier_name), locate(%(_txt)s, supplier_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530139 idx desc,
Anand Doshibd67e872014-04-11 16:51:27 +0530140 name, supplier_name
Anand Doshi48d3b542014-07-09 13:15:03 +0530141 limit %(start)s, %(page_len)s """.format(**{
Himanshud94a38e2020-05-18 14:26:26 +0530142 'field': ', '.join(fields),
Anand Doshi48d3b542014-07-09 13:15:03 +0530143 'key': searchfield,
144 'mcond':get_match_cond(doctype)
145 }), {
146 'txt': "%%%s%%" % txt,
147 '_txt': txt.replace("%", ""),
148 'start': start,
149 'page_len': page_len
150 })
Anand Doshibd67e872014-04-11 16:51:27 +0530151
Himanshud94a38e2020-05-18 14:26:26 +0530152
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530153@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530154@frappe.validate_and_sanitize_search_inputs
Nabin Hait9a380ef2013-07-16 17:24:17 +0530155def tax_account_query(doctype, txt, searchfield, start, page_len, filters):
Deepesh Gargfbf6e562020-03-31 10:45:32 +0530156 company_currency = erpnext.get_company_currency(filters.get('company'))
157
Suraj Shetty1923ef02020-08-05 19:42:25 +0530158 def get_accounts(with_account_type_filter):
159 account_type_condition = ''
160 if with_account_type_filter:
161 account_type_condition = "AND account_type in %(account_types)s"
162
163 accounts = frappe.db.sql("""
164 SELECT name, parent_account
165 FROM `tabAccount`
166 WHERE `tabAccount`.docstatus!=2
167 {account_type_condition}
168 AND is_group = 0
169 AND company = %(company)s
170 AND account_currency = %(currency)s
171 AND `{searchfield}` LIKE %(txt)s
prssannade7a2bc2020-09-21 13:57:04 +0530172 {mcond}
Suraj Shetty1923ef02020-08-05 19:42:25 +0530173 ORDER BY idx DESC, name
174 LIMIT %(offset)s, %(limit)s
prssannade7a2bc2020-09-21 13:57:04 +0530175 """.format(
176 account_type_condition=account_type_condition,
177 searchfield=searchfield,
178 mcond=get_match_cond(doctype)
179 ),
Suraj Shetty1923ef02020-08-05 19:42:25 +0530180 dict(
181 account_types=filters.get("account_type"),
182 company=filters.get("company"),
183 currency=company_currency,
184 txt="%{}%".format(txt),
185 offset=start,
186 limit=page_len
187 )
188 )
189
190 return accounts
191
192 tax_accounts = get_accounts(True)
193
Nabin Hait0c21e2a2014-03-21 11:14:49 +0530194 if not tax_accounts:
Suraj Shetty1923ef02020-08-05 19:42:25 +0530195 tax_accounts = get_accounts(False)
Anand Doshibd67e872014-04-11 16:51:27 +0530196
Nabin Hait0c21e2a2014-03-21 11:14:49 +0530197 return tax_accounts
Saurabh02875592013-07-08 18:45:55 +0530198
Himanshud94a38e2020-05-18 14:26:26 +0530199
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530200@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530201@frappe.validate_and_sanitize_search_inputs
Rushabh Mehta203cc962016-04-07 15:25:43 +0530202def item_query(doctype, txt, searchfield, start, page_len, filters, as_dict=False):
Saurabh02875592013-07-08 18:45:55 +0530203 conditions = []
Saurabhf52dc072013-07-10 13:07:49 +0530204
rohitwaghchaurec59371a2021-06-03 20:02:58 +0530205 if isinstance(filters, str):
206 filters = json.loads(filters)
207
marination3dbef9d2019-10-28 15:48:10 +0530208 #Get searchfields from meta and use in Item Link field query
marination1e754b12019-10-30 18:33:44 +0530209 meta = frappe.get_meta("Item", cached=True)
marination3dbef9d2019-10-28 15:48:10 +0530210 searchfields = meta.get_search_fields()
211
marination1e754b12019-10-30 18:33:44 +0530212 if "description" in searchfields:
213 searchfields.remove("description")
Rohit Waghchaure721b4132021-06-02 14:13:09 +0530214
Rohit Waghchaurec42312e2019-11-19 19:05:23 +0530215 columns = ''
216 extra_searchfields = [field for field in searchfields
217 if not field in ["name", "item_group", "description"]]
218
219 if extra_searchfields:
220 columns = ", " + ", ".join(extra_searchfields)
marination1e754b12019-10-30 18:33:44 +0530221
222 searchfields = searchfields + [field for field in[searchfield or "name", "item_code", "item_group", "item_name"]
223 if not field in searchfields]
marination3dbef9d2019-10-28 15:48:10 +0530224 searchfields = " or ".join([field + " like %(txt)s" for field in searchfields])
225
Rohit Waghchaure721b4132021-06-02 14:13:09 +0530226 if filters and isinstance(filters, dict) and filters.get('supplier'):
227 item_group_list = frappe.get_all('Supplier Item Group',
228 filters = {'supplier': filters.get('supplier')}, fields = ['item_group'])
229
noahjacobca2fb472021-05-12 16:25:07 +0530230 item_groups = []
231 for i in item_group_list:
232 item_groups.append(i.item_group)
233
234 del filters['supplier']
235
236 if item_groups:
237 filters['item_group'] = ['in', item_groups]
Rohit Waghchaure721b4132021-06-02 14:13:09 +0530238
Rushabh Mehtad5f9ebd2018-04-02 23:37:33 +0530239 description_cond = ''
240 if frappe.db.count('Item', cache=True) < 50000:
241 # scan description only if items are less than 50000
242 description_cond = 'or tabItem.description LIKE %(txt)s'
Prateeksha Singh984a7a72018-05-17 17:29:36 +0530243 return frappe.db.sql("""select tabItem.name,
Anand Doshibd67e872014-04-11 16:51:27 +0530244 if(length(tabItem.item_name) > 40,
245 concat(substr(tabItem.item_name, 1, 40), "..."), item_name) as item_name,
Prateeksha Singh984a7a72018-05-17 17:29:36 +0530246 tabItem.item_group,
Saurabh02875592013-07-08 18:45:55 +0530247 if(length(tabItem.description) > 40, \
Rohit Waghchaurec42312e2019-11-19 19:05:23 +0530248 concat(substr(tabItem.description, 1, 40), "..."), description) as description
marination1e754b12019-10-30 18:33:44 +0530249 {columns}
Anand Doshibd67e872014-04-11 16:51:27 +0530250 from tabItem
Anand Doshi22c0d782013-11-04 16:23:04 +0530251 where tabItem.docstatus < 2
Anand Doshi21e09a22015-10-29 12:21:41 +0530252 and tabItem.disabled=0
rohitwaghchaure79789072020-05-21 18:10:13 +0530253 and tabItem.has_variants=0
Rushabh Mehta864d1ea2014-06-23 12:20:12 +0530254 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 +0530255 and ({scond} or tabItem.item_code IN (select parent from `tabItem Barcode` where barcode LIKE %(txt)s)
Rohit Waghchaure2bfb0632019-03-02 21:47:55 +0530256 {description_cond})
Anand Doshi22c0d782013-11-04 16:23:04 +0530257 {fcond} {mcond}
Anand Doshi652bc072014-04-16 15:21:46 +0530258 order by
259 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
260 if(locate(%(_txt)s, item_name), locate(%(_txt)s, item_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530261 idx desc,
Anand Doshi652bc072014-04-16 15:21:46 +0530262 name, item_name
Rushabh Mehtabc4e2cd2017-10-17 12:30:34 +0530263 limit %(start)s, %(page_len)s """.format(
marination1e754b12019-10-30 18:33:44 +0530264 columns=columns,
marination3dbef9d2019-10-28 15:48:10 +0530265 scond=searchfields,
Nabin Haitc6285062016-03-30 13:10:25 +0530266 fcond=get_filters_cond(doctype, filters, conditions).replace('%', '%%'),
Rushabh Mehtad5f9ebd2018-04-02 23:37:33 +0530267 mcond=get_match_cond(doctype).replace('%', '%%'),
268 description_cond = description_cond),
Anand Doshi22c0d782013-11-04 16:23:04 +0530269 {
270 "today": nowdate(),
271 "txt": "%%%s%%" % txt,
Anand Doshi652bc072014-04-16 15:21:46 +0530272 "_txt": txt.replace("%", ""),
Anand Doshi22c0d782013-11-04 16:23:04 +0530273 "start": start,
274 "page_len": page_len
Rushabh Mehta203cc962016-04-07 15:25:43 +0530275 }, as_dict=as_dict)
Saurabh02875592013-07-08 18:45:55 +0530276
Himanshud94a38e2020-05-18 14:26:26 +0530277
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530278@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530279@frappe.validate_and_sanitize_search_inputs
Saurabh022ab632017-11-10 15:06:02 +0530280def bom(doctype, txt, searchfield, start, page_len, filters):
Anand Doshibd67e872014-04-11 16:51:27 +0530281 conditions = []
Himanshud94a38e2020-05-18 14:26:26 +0530282 fields = get_fields("BOM", ["name", "item"])
Saurabhf52dc072013-07-10 13:07:49 +0530283
Himanshud94a38e2020-05-18 14:26:26 +0530284 return frappe.db.sql("""select {fields}
Anand Doshibd67e872014-04-11 16:51:27 +0530285 from tabBOM
286 where tabBOM.docstatus=1
287 and tabBOM.is_active=1
Nabin Hait62211172016-03-16 16:22:03 +0530288 and tabBOM.`{key}` like %(txt)s
289 {fcond} {mcond}
290 order by
Rushabh Mehta3574b372016-03-11 14:33:04 +0530291 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
292 idx desc, name
Nabin Hait62211172016-03-16 16:22:03 +0530293 limit %(start)s, %(page_len)s """.format(
Himanshud94a38e2020-05-18 14:26:26 +0530294 fields=", ".join(fields),
Mangesh-Khairnar6a796912019-07-08 10:40:40 +0530295 fcond=get_filters_cond(doctype, filters, conditions).replace('%', '%%'),
Karthikeyan S747c2622019-07-19 22:49:21 +0530296 mcond=get_match_cond(doctype).replace('%', '%%'),
297 key=searchfield),
Mangesh-Khairnar6a796912019-07-08 10:40:40 +0530298 {
Karthikeyan S747c2622019-07-19 22:49:21 +0530299 'txt': '%' + txt + '%',
Rushabh Mehta3574b372016-03-11 14:33:04 +0530300 '_txt': txt.replace("%", ""),
Saurabh022ab632017-11-10 15:06:02 +0530301 'start': start or 0,
302 'page_len': page_len or 20
Rushabh Mehta3574b372016-03-11 14:33:04 +0530303 })
Saurabh02875592013-07-08 18:45:55 +0530304
Himanshud94a38e2020-05-18 14:26:26 +0530305
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530306@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530307@frappe.validate_and_sanitize_search_inputs
Saurabh02875592013-07-08 18:45:55 +0530308def get_project_name(doctype, txt, searchfield, start, page_len, filters):
309 cond = ''
Nabin Haitf71011a2014-08-21 11:34:31 +0530310 if filters.get('customer'):
Suraj Shetty6ea3de92018-09-26 18:15:53 +0530311 cond = """(`tabProject`.customer = %s or
rohitwaghchauree3304722018-08-27 11:43:57 +0530312 ifnull(`tabProject`.customer,"")="") and""" %(frappe.db.escape(filters.get("customer")))
Anand Doshibd67e872014-04-11 16:51:27 +0530313
Rucha Mahabal062d3012021-05-07 13:31:14 +0530314 fields = get_fields("Project", ["name", "project_name"])
315 searchfields = frappe.get_meta("Project").get_search_fields()
316 searchfields = " or ".join([field + " like %(txt)s" for field in searchfields])
Himanshud94a38e2020-05-18 14:26:26 +0530317
318 return frappe.db.sql("""select {fields} from `tabProject`
Rucha Mahabal062d3012021-05-07 13:31:14 +0530319 where
320 `tabProject`.status not in ("Completed", "Cancelled")
Subin Tom889140f2021-06-22 16:26:19 +0530321 and {cond} {scond} {match_cond}
Rushabh Mehta3574b372016-03-11 14:33:04 +0530322 order by
323 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
324 idx desc,
325 `tabProject`.name asc
326 limit {start}, {page_len}""".format(
Himanshud94a38e2020-05-18 14:26:26 +0530327 fields=", ".join(['`tabProject`.{0}'.format(f) for f in fields]),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530328 cond=cond,
Rucha Mahabal062d3012021-05-07 13:31:14 +0530329 scond=searchfields,
Rushabh Mehta3574b372016-03-11 14:33:04 +0530330 match_cond=get_match_cond(doctype),
331 start=start,
332 page_len=page_len), {
333 "txt": "%{0}%".format(txt),
Nabin Haitdf4deba2016-03-16 11:16:31 +0530334 "_txt": txt.replace('%', '')
Rushabh Mehta3574b372016-03-11 14:33:04 +0530335 })
Anand Doshibd67e872014-04-11 16:51:27 +0530336
tundebabzyf6d738b2017-09-18 12:40:09 +0100337
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530338@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530339@frappe.validate_and_sanitize_search_inputs
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530340def get_delivery_notes_to_be_billed(doctype, txt, searchfield, start, page_len, filters, as_dict):
Himanshud94a38e2020-05-18 14:26:26 +0530341 fields = get_fields("Delivery Note", ["name", "customer", "posting_date"])
342
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530343 return frappe.db.sql("""
Himanshud94a38e2020-05-18 14:26:26 +0530344 select %(fields)s
Anand Doshibd67e872014-04-11 16:51:27 +0530345 from `tabDelivery Note`
346 where `tabDelivery Note`.`%(key)s` like %(txt)s and
tundebabzyf6d738b2017-09-18 12:40:09 +0100347 `tabDelivery Note`.docstatus = 1
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530348 and status not in ("Stopped", "Closed") %(fcond)s
tundebabzyf6d738b2017-09-18 12:40:09 +0100349 and (
350 (`tabDelivery Note`.is_return = 0 and `tabDelivery Note`.per_billed < 100)
Deepesh Garge2dc1022021-04-14 11:21:11 +0530351 or (`tabDelivery Note`.grand_total = 0 and `tabDelivery Note`.per_billed < 100)
tundebabzyf6d738b2017-09-18 12:40:09 +0100352 or (
353 `tabDelivery Note`.is_return = 1
354 and return_against in (select name from `tabDelivery Note` where per_billed < 100)
355 )
356 )
rohitwaghchaured07a3e12019-05-15 07:46:28 +0530357 %(mcond)s order by `tabDelivery Note`.`%(key)s` asc limit %(start)s, %(page_len)s
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530358 """ % {
Himanshud94a38e2020-05-18 14:26:26 +0530359 "fields": ", ".join(["`tabDelivery Note`.{0}".format(f) for f in fields]),
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530360 "key": searchfield,
361 "fcond": get_filters_cond(doctype, filters, []),
362 "mcond": get_match_cond(doctype),
rohitwaghchaured07a3e12019-05-15 07:46:28 +0530363 "start": start,
364 "page_len": page_len,
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530365 "txt": "%(txt)s"
tundebabzyf6d738b2017-09-18 12:40:09 +0100366 }, {"txt": ("%%%s%%" % txt)}, as_dict=as_dict)
367
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530368
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530369@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530370@frappe.validate_and_sanitize_search_inputs
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530371def get_batch_no(doctype, txt, searchfield, start, page_len, filters):
Neil Trini Lasradoebb60f52015-07-08 14:36:09 +0530372 cond = ""
373 if filters.get("posting_date"):
Nabin Hait7918b922018-01-31 15:30:03 +0530374 cond = "and (batch.expiry_date is null or batch.expiry_date >= %(posting_date)s)"
Rushabh Mehtab6398be2015-08-26 10:50:16 +0530375
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530376 batch_nos = None
377 args = {
378 'item_code': filters.get("item_code"),
379 'warehouse': filters.get("warehouse"),
380 'posting_date': filters.get('posting_date'),
Anand Doshi0dc79f42015-04-06 12:59:34 +0530381 'txt': "%{0}%".format(txt),
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530382 "start": start,
383 "page_len": page_len
384 }
385
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530386 having_clause = "having sum(sle.actual_qty) > 0"
387 if filters.get("is_return"):
388 having_clause = ""
389
Deepesh Garga0d192e2020-09-22 13:54:07 +0530390 meta = frappe.get_meta("Batch", cached=True)
391 searchfields = meta.get_search_fields()
392
393 search_columns = ''
Deepesh Gargf58a5ec2020-10-05 13:55:53 +0530394 search_cond = ''
395
Deepesh Garga0d192e2020-09-22 13:54:07 +0530396 if searchfields:
397 search_columns = ", " + ", ".join(searchfields)
Deepesh Garg1fae7742020-10-05 12:38:54 +0530398 search_cond = " or " + " or ".join([field + " like %(txt)s" for field in searchfields])
Deepesh Garga0d192e2020-09-22 13:54:07 +0530399
Anand Doshi0dc79f42015-04-06 12:59:34 +0530400 if args.get('warehouse'):
Deepesh Garga0d192e2020-09-22 13:54:07 +0530401 searchfields = ['batch.' + field for field in searchfields]
402 if searchfields:
403 search_columns = ", " + ", ".join(searchfields)
Deepesh Garg1fae7742020-10-05 12:38:54 +0530404 search_cond = " or " + " or ".join([field + " like %(txt)s" for field in searchfields])
Deepesh Garga0d192e2020-09-22 13:54:07 +0530405
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530406 batch_nos = frappe.db.sql("""select sle.batch_no, round(sum(sle.actual_qty),2), sle.stock_uom,
407 concat('MFG-',batch.manufacturing_date), concat('EXP-',batch.expiry_date)
Deepesh Garga0d192e2020-09-22 13:54:07 +0530408 {search_columns}
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530409 from `tabStock Ledger Entry` sle
410 INNER JOIN `tabBatch` batch on sle.batch_no = batch.name
411 where
412 batch.disabled = 0
Rohit Waghchaurec14aa452021-07-20 18:19:15 +0530413 and sle.is_cancelled = 0
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530414 and sle.item_code = %(item_code)s
415 and sle.warehouse = %(warehouse)s
416 and (sle.batch_no like %(txt)s
Sun Howwrongbum088be372019-12-24 12:29:25 +0530417 or batch.expiry_date like %(txt)s
Deepesh Gargf58a5ec2020-10-05 13:55:53 +0530418 or batch.manufacturing_date like %(txt)s
419 {search_cond})
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530420 and batch.docstatus < 2
421 {cond}
422 {match_conditions}
423 group by batch_no {having_clause}
424 order by batch.expiry_date, sle.batch_no desc
425 limit %(start)s, %(page_len)s""".format(
Deepesh Garga0d192e2020-09-22 13:54:07 +0530426 search_columns = search_columns,
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530427 cond=cond,
428 match_conditions=get_match_cond(doctype),
Deepesh Garg1fae7742020-10-05 12:38:54 +0530429 having_clause = having_clause,
430 search_cond = search_cond
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530431 ), args)
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530432
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530433 return batch_nos
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530434 else:
Deepesh Garga0d192e2020-09-22 13:54:07 +0530435 return frappe.db.sql("""select name, concat('MFG-', manufacturing_date), concat('EXP-',expiry_date)
436 {search_columns}
437 from `tabBatch` batch
Doridel Cahanap59e4c322018-08-06 17:15:18 +0800438 where batch.disabled = 0
439 and item = %(item_code)s
sivankar621740e2018-02-12 14:33:40 +0530440 and (name like %(txt)s
Sun Howwrongbum088be372019-12-24 12:29:25 +0530441 or expiry_date like %(txt)s
Deepesh Gargf58a5ec2020-10-05 13:55:53 +0530442 or manufacturing_date like %(txt)s
443 {search_cond})
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530444 and docstatus < 2
Neil Trini Lasradoebb60f52015-07-08 14:36:09 +0530445 {0}
Anand Doshi0dc79f42015-04-06 12:59:34 +0530446 {match_conditions}
Deepesh Gargf58a5ec2020-10-05 13:55:53 +0530447
Anand Doshi0dc79f42015-04-06 12:59:34 +0530448 order by expiry_date, name desc
Deepesh Garg1fae7742020-10-05 12:38:54 +0530449 limit %(start)s, %(page_len)s""".format(cond, search_columns = search_columns,
450 search_cond = search_cond, match_conditions=get_match_cond(doctype)), args)
Nabin Haitea4aa042014-05-28 12:56:28 +0530451
Himanshud94a38e2020-05-18 14:26:26 +0530452
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530453@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530454@frappe.validate_and_sanitize_search_inputs
Nabin Haitea4aa042014-05-28 12:56:28 +0530455def get_account_list(doctype, txt, searchfield, start, page_len, filters):
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530456 filter_list = []
Nabin Haitea4aa042014-05-28 12:56:28 +0530457
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530458 if isinstance(filters, dict):
459 for key, val in filters.items():
460 if isinstance(val, (list, tuple)):
461 filter_list.append([doctype, key, val[0], val[1]])
462 else:
463 filter_list.append([doctype, key, "=", val])
bhupeshg2e2e973f2015-04-14 22:15:24 +0530464 elif isinstance(filters, list):
465 filter_list.extend(filters)
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530466
Rushabh Mehta38c6b522015-04-23 13:14:17 +0530467 if "is_group" not in [d[1] for d in filter_list]:
468 filter_list.append(["Account", "is_group", "=", "0"])
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530469
470 if searchfield and txt:
471 filter_list.append([doctype, searchfield, "like", "%%%s%%" % txt])
472
Rushabh Mehtac0bb4532014-09-09 16:15:35 +0530473 return frappe.desk.reportview.execute("Account", filters = filter_list,
Nabin Haitea4aa042014-05-28 12:56:28 +0530474 fields = ["name", "parent_account"],
475 limit_start=start, limit_page_length=page_len, as_list=True)
Anand Doshifaefeaa2014-06-24 18:53:04 +0530476
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530477@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530478@frappe.validate_and_sanitize_search_inputs
Marica299e2172020-04-28 13:00:04 +0530479def get_blanket_orders(doctype, txt, searchfield, start, page_len, filters):
480 return frappe.db.sql("""select distinct bo.name, bo.blanket_order_type, bo.to_date
481 from `tabBlanket Order` bo, `tabBlanket Order Item` boi
482 where
483 boi.parent = bo.name
484 and boi.item_code = {item_code}
485 and bo.blanket_order_type = '{blanket_order_type}'
486 and bo.company = {company}
487 and bo.docstatus = 1"""
488 .format(item_code = frappe.db.escape(filters.get("item")),
489 blanket_order_type = filters.get("blanket_order_type"),
490 company = frappe.db.escape(filters.get("company"))
491 ))
Nabin Haitafd14f62015-10-19 11:55:28 +0530492
Himanshud94a38e2020-05-18 14:26:26 +0530493
Nabin Haitafd14f62015-10-19 11:55:28 +0530494@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530495@frappe.validate_and_sanitize_search_inputs
Nabin Haitafd14f62015-10-19 11:55:28 +0530496def get_income_account(doctype, txt, searchfield, start, page_len, filters):
497 from erpnext.controllers.queries import get_match_cond
498
499 # income account can be any Credit account,
500 # but can also be a Asset account with account_type='Income Account' in special circumstances.
501 # Hence the first condition is an "OR"
502 if not filters: filters = {}
503
Anand Doshi21e09a22015-10-29 12:21:41 +0530504 condition = ""
Nabin Haitafd14f62015-10-19 11:55:28 +0530505 if filters.get("company"):
506 condition += "and tabAccount.company = %(company)s"
Anand Doshi21e09a22015-10-29 12:21:41 +0530507
Nabin Haitafd14f62015-10-19 11:55:28 +0530508 return frappe.db.sql("""select tabAccount.name from `tabAccount`
509 where (tabAccount.report_type = "Profit and Loss"
510 or tabAccount.account_type in ("Income Account", "Temporary"))
511 and tabAccount.is_group=0
512 and tabAccount.`{key}` LIKE %(txt)s
Rushabh Mehta3574b372016-03-11 14:33:04 +0530513 {condition} {match_condition}
514 order by idx desc, name"""
Nabin Haitafd14f62015-10-19 11:55:28 +0530515 .format(condition=condition, match_condition=get_match_cond(doctype), key=searchfield), {
Suraj Shetty4b404c42018-09-27 15:39:34 +0530516 'txt': '%' + txt + '%',
Nabin Haitafd14f62015-10-19 11:55:28 +0530517 'company': filters.get("company", "")
Anand Doshi21e09a22015-10-29 12:21:41 +0530518 })
Nabin Hait3a15c922016-03-04 12:30:46 +0530519
Deepesh Garg96e874b2020-11-15 22:43:01 +0530520@frappe.whitelist()
521@frappe.validate_and_sanitize_search_inputs
522def get_filtered_dimensions(doctype, txt, searchfield, start, page_len, filters):
Chillar Anand915b3432021-09-02 16:44:59 +0530523 from erpnext.accounts.doctype.accounting_dimension_filter.accounting_dimension_filter import (
524 get_dimension_filter_map,
525 )
Deepesh Garg96e874b2020-11-15 22:43:01 +0530526 dimension_filters = get_dimension_filter_map()
527 dimension_filters = dimension_filters.get((filters.get('dimension'),filters.get('account')))
Deepesh Garg6c17b842020-11-25 13:42:16 +0530528 query_filters = []
Deepesh Garg96e874b2020-11-15 22:43:01 +0530529
530 meta = frappe.get_meta(doctype)
Deepesh Garg96e874b2020-11-15 22:43:01 +0530531 if meta.is_tree:
Deepesh Garg6c17b842020-11-25 13:42:16 +0530532 query_filters.append(['is_group', '=', 0])
Deepesh Garg96e874b2020-11-15 22:43:01 +0530533
Subin Tom333e44e2021-08-18 16:17:54 +0530534 if meta.has_field('disabled'):
535 query_filters.append(['disabled', '!=', 1])
536
Deepesh Garg96e874b2020-11-15 22:43:01 +0530537 if meta.has_field('company'):
Deepesh Garg6c17b842020-11-25 13:42:16 +0530538 query_filters.append(['company', '=', filters.get('company')])
539
540 if txt:
541 query_filters.append([searchfield, 'LIKE', "%%%s%%" % txt])
Deepesh Garg96e874b2020-11-15 22:43:01 +0530542
543 if dimension_filters:
544 if dimension_filters['allow_or_restrict'] == 'Allow':
545 query_selector = 'in'
546 else:
547 query_selector = 'not in'
548
549 if len(dimension_filters['allowed_dimensions']) == 1:
550 dimensions = tuple(dimension_filters['allowed_dimensions'] * 2)
551 else:
552 dimensions = tuple(dimension_filters['allowed_dimensions'])
553
Deepesh Garg6c17b842020-11-25 13:42:16 +0530554 query_filters.append(['name', query_selector, dimensions])
Deepesh Garg96e874b2020-11-15 22:43:01 +0530555
Deepesh Garg6c17b842020-11-25 13:42:16 +0530556 output = frappe.get_all(doctype, filters=query_filters)
557 result = [d.name for d in output]
558
559 return [(d,) for d in set(result)]
Nabin Hait3a15c922016-03-04 12:30:46 +0530560
561@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530562@frappe.validate_and_sanitize_search_inputs
Nabin Hait3a15c922016-03-04 12:30:46 +0530563def get_expense_account(doctype, txt, searchfield, start, page_len, filters):
564 from erpnext.controllers.queries import get_match_cond
Rushabh Mehta203cc962016-04-07 15:25:43 +0530565
Nabin Hait3a15c922016-03-04 12:30:46 +0530566 if not filters: filters = {}
567
568 condition = ""
569 if filters.get("company"):
570 condition += "and tabAccount.company = %(company)s"
Rushabh Mehta203cc962016-04-07 15:25:43 +0530571
Nabin Hait3a15c922016-03-04 12:30:46 +0530572 return frappe.db.sql("""select tabAccount.name from `tabAccount`
573 where (tabAccount.report_type = "Profit and Loss"
Mangesh-Khairnar5619db22019-08-21 14:49:24 +0530574 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 +0530575 and tabAccount.is_group=0
576 and tabAccount.docstatus!=2
577 and tabAccount.{key} LIKE %(txt)s
578 {condition} {match_condition}"""
Suraj Shettybfc195d2018-09-21 10:20:52 +0530579 .format(condition=condition, key=searchfield,
Nabin Hait3a15c922016-03-04 12:30:46 +0530580 match_condition=get_match_cond(doctype)), {
Neil Trini Lasrado30b97b02016-03-31 23:10:13 +0530581 'company': filters.get("company", ""),
Suraj Shetty4b404c42018-09-27 15:39:34 +0530582 'txt': '%' + txt + '%'
Maxwell Morais35572612016-07-21 23:42:59 -0300583 })
suyashphadtare049a88c2017-01-12 17:49:37 +0530584
585
586@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530587@frappe.validate_and_sanitize_search_inputs
suyashphadtare049a88c2017-01-12 17:49:37 +0530588def warehouse_query(doctype, txt, searchfield, start, page_len, filters):
589 # Should be used when item code is passed in filters.
suyashphadtare750a0672017-01-18 15:35:01 +0530590 conditions, bin_conditions = [], []
591 filter_dict = get_doctype_wise_filters(filters)
592
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530593 query = """select `tabWarehouse`.name,
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530594 CONCAT_WS(" : ", "Actual Qty", ifnull(round(`tabBin`.actual_qty, 2), 0 )) actual_qty
595 from `tabWarehouse` left join `tabBin`
596 on `tabBin`.warehouse = `tabWarehouse`.name {bin_conditions}
suyashphadtare34ab1362017-01-31 15:14:44 +0530597 where
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530598 `tabWarehouse`.`{key}` like {txt}
suyashphadtare34ab1362017-01-31 15:14:44 +0530599 {fcond} {mcond}
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530600 order by ifnull(`tabBin`.actual_qty, 0) desc
suyashphadtare34ab1362017-01-31 15:14:44 +0530601 limit
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530602 {start}, {page_len}
suyashphadtare34ab1362017-01-31 15:14:44 +0530603 """.format(
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530604 bin_conditions=get_filters_cond(doctype, filter_dict.get("Bin"),bin_conditions, ignore_permissions=True),
Suraj Shettybfc195d2018-09-21 10:20:52 +0530605 key=searchfield,
suyashphadtare34ab1362017-01-31 15:14:44 +0530606 fcond=get_filters_cond(doctype, filter_dict.get("Warehouse"), conditions),
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530607 mcond=get_match_cond(doctype),
608 start=start,
609 page_len=page_len,
610 txt=frappe.db.escape('%{0}%'.format(txt))
611 )
612
613 return frappe.db.sql(query)
suyashphadtare750a0672017-01-18 15:35:01 +0530614
615
616def get_doctype_wise_filters(filters):
617 # Helper function to seperate filters doctype_wise
618 filter_dict = defaultdict(list)
619 for row in filters:
620 filter_dict[row[0]].append(row)
621 return filter_dict
tundebabzy2a4fefc2017-11-29 06:23:09 +0100622
623
624@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530625@frappe.validate_and_sanitize_search_inputs
tundebabzy2a4fefc2017-11-29 06:23:09 +0100626def get_batch_numbers(doctype, txt, searchfield, start, page_len, filters):
rohitwaghchaure9fbed562018-01-12 16:22:33 +0530627 query = """select batch_id from `tabBatch`
Doridel Cahanap59e4c322018-08-06 17:15:18 +0800628 where disabled = 0
629 and (expiry_date >= CURDATE() or expiry_date IS NULL)
Suraj Shettybfc195d2018-09-21 10:20:52 +0530630 and name like {txt}""".format(txt = frappe.db.escape('%{0}%'.format(txt)))
tundebabzy2a4fefc2017-11-29 06:23:09 +0100631
rohitwaghchaure9fbed562018-01-12 16:22:33 +0530632 if filters and filters.get('item'):
Suraj Shettybfc195d2018-09-21 10:20:52 +0530633 query += " and item = {item}".format(item = frappe.db.escape(filters.get('item')))
tundebabzy2a4fefc2017-11-29 06:23:09 +0100634
Sachin Mane64f48db2018-01-08 17:57:32 +0530635 return frappe.db.sql(query, filters)
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530636
Himanshud94a38e2020-05-18 14:26:26 +0530637
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530638@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530639@frappe.validate_and_sanitize_search_inputs
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530640def item_manufacturer_query(doctype, txt, searchfield, start, page_len, filters):
Maricabac4b932019-09-16 19:44:28 +0530641 item_filters = [
642 ['manufacturer', 'like', '%' + txt + '%'],
643 ['item_code', '=', filters.get("item_code")]
644 ]
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530645
Maricabac4b932019-09-16 19:44:28 +0530646 item_manufacturers = frappe.get_all(
647 "Item Manufacturer",
648 fields=["manufacturer", "manufacturer_part_no"],
649 filters=item_filters,
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530650 limit_start=start,
651 limit_page_length=page_len,
652 as_list=1
653 )
Maricabac4b932019-09-16 19:44:28 +0530654 return item_manufacturers
Saqibd9956092019-11-18 11:46:55 +0530655
Himanshud94a38e2020-05-18 14:26:26 +0530656
Saqibd9956092019-11-18 11:46:55 +0530657@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530658@frappe.validate_and_sanitize_search_inputs
Saqibd9956092019-11-18 11:46:55 +0530659def get_purchase_receipts(doctype, txt, searchfield, start, page_len, filters):
660 query = """
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530661 select pr.name
Saqibd9956092019-11-18 11:46:55 +0530662 from `tabPurchase Receipt` pr, `tabPurchase Receipt Item` pritem
663 where pr.docstatus = 1 and pritem.parent = pr.name
664 and pr.name like {txt}""".format(txt = frappe.db.escape('%{0}%'.format(txt)))
665
666 if filters and filters.get('item_code'):
667 query += " and pritem.item_code = {item_code}".format(item_code = frappe.db.escape(filters.get('item_code')))
668
669 return frappe.db.sql(query, filters)
670
Himanshud94a38e2020-05-18 14:26:26 +0530671
Saqibd9956092019-11-18 11:46:55 +0530672@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530673@frappe.validate_and_sanitize_search_inputs
Saqibd9956092019-11-18 11:46:55 +0530674def get_purchase_invoices(doctype, txt, searchfield, start, page_len, filters):
675 query = """
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530676 select pi.name
Saqibd9956092019-11-18 11:46:55 +0530677 from `tabPurchase Invoice` pi, `tabPurchase Invoice Item` piitem
678 where pi.docstatus = 1 and piitem.parent = pi.name
679 and pi.name like {txt}""".format(txt = frappe.db.escape('%{0}%'.format(txt)))
680
681 if filters and filters.get('item_code'):
682 query += " and piitem.item_code = {item_code}".format(item_code = frappe.db.escape(filters.get('item_code')))
683
684 return frappe.db.sql(query, filters)
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530685
Himanshud94a38e2020-05-18 14:26:26 +0530686
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530687@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530688@frappe.validate_and_sanitize_search_inputs
Rucha Mahabal20e53152021-01-18 14:56:55 +0530689def get_healthcare_service_units(doctype, txt, searchfield, start, page_len, filters):
690 query = """
691 select name
692 from `tabHealthcare Service Unit`
693 where
694 is_group = 0
695 and company = {company}
696 and name like {txt}""".format(
697 company = frappe.db.escape(filters.get('company')), txt = frappe.db.escape('%{0}%'.format(txt)))
698
699 if filters and filters.get('inpatient_record'):
Chillar Anand915b3432021-09-02 16:44:59 +0530700 from erpnext.healthcare.doctype.inpatient_medication_entry.inpatient_medication_entry import (
701 get_current_healthcare_service_unit,
702 )
Rucha Mahabal20e53152021-01-18 14:56:55 +0530703 service_unit = get_current_healthcare_service_unit(filters.get('inpatient_record'))
704
705 # if the patient is admitted, then appointments should be allowed against the admission service unit,
706 # inspite of it being an Inpatient Occupancy service unit
707 if service_unit:
708 query += " and (allow_appointments = 1 or name = {service_unit})".format(service_unit = frappe.db.escape(service_unit))
709 else:
710 query += " and allow_appointments = 1"
711 else:
712 query += " and allow_appointments = 1"
713
714 return frappe.db.sql(query, filters)
715
716
717@frappe.whitelist()
718@frappe.validate_and_sanitize_search_inputs
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530719def get_tax_template(doctype, txt, searchfield, start, page_len, filters):
720
721 item_doc = frappe.get_cached_doc('Item', filters.get('item_code'))
722 item_group = filters.get('item_group')
723 taxes = item_doc.taxes or []
724
725 while item_group:
726 item_group_doc = frappe.get_cached_doc('Item Group', item_group)
727 taxes += item_group_doc.taxes or []
728 item_group = item_group_doc.parent_item_group
729
730 if not taxes:
731 return frappe.db.sql(""" SELECT name FROM `tabItem Tax Template` """)
732 else:
Marica0fcb05a2020-08-10 14:48:13 +0530733 valid_from = filters.get('valid_from')
734 valid_from = valid_from[1] if isinstance(valid_from, list) else valid_from
735
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530736 args = {
737 'item_code': filters.get('item_code'),
Marica0fcb05a2020-08-10 14:48:13 +0530738 'posting_date': valid_from,
mohammadahmad199041c0c9f2020-06-18 11:18:44 +0500739 'tax_category': filters.get('tax_category'),
740 'company': filters.get('company')
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530741 }
742
743 taxes = _get_item_tax_template(args, taxes, for_validate=True)
744 return [(d,) for d in set(taxes)]
Himanshud94a38e2020-05-18 14:26:26 +0530745
746
Ankush Menat7eac4a22021-04-19 10:33:39 +0530747def get_fields(doctype, fields=None):
748 if fields is None:
749 fields = []
Himanshud94a38e2020-05-18 14:26:26 +0530750 meta = frappe.get_meta(doctype)
751 fields.extend(meta.get_search_fields())
752
753 if meta.title_field and not meta.title_field.strip() in fields:
754 fields.insert(1, meta.title_field.strip())
755
756 return unique(fields)