blob: 638503edfa9065a127df3808a79b2ac86fdb7c03 [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")
Rohit Waghchaure721b4132021-06-02 14:13:09 +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
Rohit Waghchaure721b4132021-06-02 14:13:09 +0530219 if filters and isinstance(filters, dict) and filters.get('supplier'):
220 item_group_list = frappe.get_all('Supplier Item Group',
221 filters = {'supplier': filters.get('supplier')}, fields = ['item_group'])
222
noahjacobca2fb472021-05-12 16:25:07 +0530223 item_groups = []
224 for i in item_group_list:
225 item_groups.append(i.item_group)
226
227 del filters['supplier']
228
229 if item_groups:
230 filters['item_group'] = ['in', item_groups]
Rohit Waghchaure721b4132021-06-02 14:13:09 +0530231
Rushabh Mehtad5f9ebd2018-04-02 23:37:33 +0530232 description_cond = ''
233 if frappe.db.count('Item', cache=True) < 50000:
234 # scan description only if items are less than 50000
235 description_cond = 'or tabItem.description LIKE %(txt)s'
Prateeksha Singh984a7a72018-05-17 17:29:36 +0530236 return frappe.db.sql("""select tabItem.name,
Anand Doshibd67e872014-04-11 16:51:27 +0530237 if(length(tabItem.item_name) > 40,
238 concat(substr(tabItem.item_name, 1, 40), "..."), item_name) as item_name,
Prateeksha Singh984a7a72018-05-17 17:29:36 +0530239 tabItem.item_group,
Saurabh02875592013-07-08 18:45:55 +0530240 if(length(tabItem.description) > 40, \
Rohit Waghchaurec42312e2019-11-19 19:05:23 +0530241 concat(substr(tabItem.description, 1, 40), "..."), description) as description
marination1e754b12019-10-30 18:33:44 +0530242 {columns}
Anand Doshibd67e872014-04-11 16:51:27 +0530243 from tabItem
Anand Doshi22c0d782013-11-04 16:23:04 +0530244 where tabItem.docstatus < 2
Anand Doshi21e09a22015-10-29 12:21:41 +0530245 and tabItem.disabled=0
rohitwaghchaure79789072020-05-21 18:10:13 +0530246 and tabItem.has_variants=0
Rushabh Mehta864d1ea2014-06-23 12:20:12 +0530247 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 +0530248 and ({scond} or tabItem.item_code IN (select parent from `tabItem Barcode` where barcode LIKE %(txt)s)
Rohit Waghchaure2bfb0632019-03-02 21:47:55 +0530249 {description_cond})
Anand Doshi22c0d782013-11-04 16:23:04 +0530250 {fcond} {mcond}
Anand Doshi652bc072014-04-16 15:21:46 +0530251 order by
252 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
253 if(locate(%(_txt)s, item_name), locate(%(_txt)s, item_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530254 idx desc,
Anand Doshi652bc072014-04-16 15:21:46 +0530255 name, item_name
Rushabh Mehtabc4e2cd2017-10-17 12:30:34 +0530256 limit %(start)s, %(page_len)s """.format(
marination1e754b12019-10-30 18:33:44 +0530257 columns=columns,
marination3dbef9d2019-10-28 15:48:10 +0530258 scond=searchfields,
Nabin Haitc6285062016-03-30 13:10:25 +0530259 fcond=get_filters_cond(doctype, filters, conditions).replace('%', '%%'),
Rushabh Mehtad5f9ebd2018-04-02 23:37:33 +0530260 mcond=get_match_cond(doctype).replace('%', '%%'),
261 description_cond = description_cond),
Anand Doshi22c0d782013-11-04 16:23:04 +0530262 {
263 "today": nowdate(),
264 "txt": "%%%s%%" % txt,
Anand Doshi652bc072014-04-16 15:21:46 +0530265 "_txt": txt.replace("%", ""),
Anand Doshi22c0d782013-11-04 16:23:04 +0530266 "start": start,
267 "page_len": page_len
Rushabh Mehta203cc962016-04-07 15:25:43 +0530268 }, as_dict=as_dict)
Saurabh02875592013-07-08 18:45:55 +0530269
Himanshud94a38e2020-05-18 14:26:26 +0530270
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530271@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530272@frappe.validate_and_sanitize_search_inputs
Saurabh022ab632017-11-10 15:06:02 +0530273def bom(doctype, txt, searchfield, start, page_len, filters):
Anand Doshibd67e872014-04-11 16:51:27 +0530274 conditions = []
Himanshud94a38e2020-05-18 14:26:26 +0530275 fields = get_fields("BOM", ["name", "item"])
Saurabhf52dc072013-07-10 13:07:49 +0530276
Himanshud94a38e2020-05-18 14:26:26 +0530277 return frappe.db.sql("""select {fields}
Anand Doshibd67e872014-04-11 16:51:27 +0530278 from tabBOM
279 where tabBOM.docstatus=1
280 and tabBOM.is_active=1
Nabin Hait62211172016-03-16 16:22:03 +0530281 and tabBOM.`{key}` like %(txt)s
282 {fcond} {mcond}
283 order by
Rushabh Mehta3574b372016-03-11 14:33:04 +0530284 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
285 idx desc, name
Nabin Hait62211172016-03-16 16:22:03 +0530286 limit %(start)s, %(page_len)s """.format(
Himanshud94a38e2020-05-18 14:26:26 +0530287 fields=", ".join(fields),
Mangesh-Khairnar6a796912019-07-08 10:40:40 +0530288 fcond=get_filters_cond(doctype, filters, conditions).replace('%', '%%'),
Karthikeyan S747c2622019-07-19 22:49:21 +0530289 mcond=get_match_cond(doctype).replace('%', '%%'),
290 key=searchfield),
Mangesh-Khairnar6a796912019-07-08 10:40:40 +0530291 {
Karthikeyan S747c2622019-07-19 22:49:21 +0530292 'txt': '%' + txt + '%',
Rushabh Mehta3574b372016-03-11 14:33:04 +0530293 '_txt': txt.replace("%", ""),
Saurabh022ab632017-11-10 15:06:02 +0530294 'start': start or 0,
295 'page_len': page_len or 20
Rushabh Mehta3574b372016-03-11 14:33:04 +0530296 })
Saurabh02875592013-07-08 18:45:55 +0530297
Himanshud94a38e2020-05-18 14:26:26 +0530298
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530299@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530300@frappe.validate_and_sanitize_search_inputs
Saurabh02875592013-07-08 18:45:55 +0530301def get_project_name(doctype, txt, searchfield, start, page_len, filters):
302 cond = ''
Nabin Haitf71011a2014-08-21 11:34:31 +0530303 if filters.get('customer'):
Suraj Shetty6ea3de92018-09-26 18:15:53 +0530304 cond = """(`tabProject`.customer = %s or
rohitwaghchauree3304722018-08-27 11:43:57 +0530305 ifnull(`tabProject`.customer,"")="") and""" %(frappe.db.escape(filters.get("customer")))
Anand Doshibd67e872014-04-11 16:51:27 +0530306
Rucha Mahabal062d3012021-05-07 13:31:14 +0530307 fields = get_fields("Project", ["name", "project_name"])
308 searchfields = frappe.get_meta("Project").get_search_fields()
309 searchfields = " or ".join([field + " like %(txt)s" for field in searchfields])
Himanshud94a38e2020-05-18 14:26:26 +0530310
311 return frappe.db.sql("""select {fields} from `tabProject`
Rucha Mahabal062d3012021-05-07 13:31:14 +0530312 where
313 `tabProject`.status not in ("Completed", "Cancelled")
314 and {cond} {match_cond} {scond}
Rushabh Mehta3574b372016-03-11 14:33:04 +0530315 order by
316 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
317 idx desc,
318 `tabProject`.name asc
319 limit {start}, {page_len}""".format(
Himanshud94a38e2020-05-18 14:26:26 +0530320 fields=", ".join(['`tabProject`.{0}'.format(f) for f in fields]),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530321 cond=cond,
Rucha Mahabal062d3012021-05-07 13:31:14 +0530322 scond=searchfields,
Rushabh Mehta3574b372016-03-11 14:33:04 +0530323 match_cond=get_match_cond(doctype),
324 start=start,
325 page_len=page_len), {
326 "txt": "%{0}%".format(txt),
Nabin Haitdf4deba2016-03-16 11:16:31 +0530327 "_txt": txt.replace('%', '')
Rushabh Mehta3574b372016-03-11 14:33:04 +0530328 })
Anand Doshibd67e872014-04-11 16:51:27 +0530329
tundebabzyf6d738b2017-09-18 12:40:09 +0100330
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530331@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530332@frappe.validate_and_sanitize_search_inputs
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530333def get_delivery_notes_to_be_billed(doctype, txt, searchfield, start, page_len, filters, as_dict):
Himanshud94a38e2020-05-18 14:26:26 +0530334 fields = get_fields("Delivery Note", ["name", "customer", "posting_date"])
335
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530336 return frappe.db.sql("""
Himanshud94a38e2020-05-18 14:26:26 +0530337 select %(fields)s
Anand Doshibd67e872014-04-11 16:51:27 +0530338 from `tabDelivery Note`
339 where `tabDelivery Note`.`%(key)s` like %(txt)s and
tundebabzyf6d738b2017-09-18 12:40:09 +0100340 `tabDelivery Note`.docstatus = 1
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530341 and status not in ("Stopped", "Closed") %(fcond)s
tundebabzyf6d738b2017-09-18 12:40:09 +0100342 and (
343 (`tabDelivery Note`.is_return = 0 and `tabDelivery Note`.per_billed < 100)
Deepesh Garge2dc1022021-04-14 11:21:11 +0530344 or (`tabDelivery Note`.grand_total = 0 and `tabDelivery Note`.per_billed < 100)
tundebabzyf6d738b2017-09-18 12:40:09 +0100345 or (
346 `tabDelivery Note`.is_return = 1
347 and return_against in (select name from `tabDelivery Note` where per_billed < 100)
348 )
349 )
rohitwaghchaured07a3e12019-05-15 07:46:28 +0530350 %(mcond)s order by `tabDelivery Note`.`%(key)s` asc limit %(start)s, %(page_len)s
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530351 """ % {
Himanshud94a38e2020-05-18 14:26:26 +0530352 "fields": ", ".join(["`tabDelivery Note`.{0}".format(f) for f in fields]),
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530353 "key": searchfield,
354 "fcond": get_filters_cond(doctype, filters, []),
355 "mcond": get_match_cond(doctype),
rohitwaghchaured07a3e12019-05-15 07:46:28 +0530356 "start": start,
357 "page_len": page_len,
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530358 "txt": "%(txt)s"
tundebabzyf6d738b2017-09-18 12:40:09 +0100359 }, {"txt": ("%%%s%%" % txt)}, as_dict=as_dict)
360
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530361
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530362@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530363@frappe.validate_and_sanitize_search_inputs
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530364def get_batch_no(doctype, txt, searchfield, start, page_len, filters):
Neil Trini Lasradoebb60f52015-07-08 14:36:09 +0530365 cond = ""
366 if filters.get("posting_date"):
Nabin Hait7918b922018-01-31 15:30:03 +0530367 cond = "and (batch.expiry_date is null or batch.expiry_date >= %(posting_date)s)"
Rushabh Mehtab6398be2015-08-26 10:50:16 +0530368
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530369 batch_nos = None
370 args = {
371 'item_code': filters.get("item_code"),
372 'warehouse': filters.get("warehouse"),
373 'posting_date': filters.get('posting_date'),
Anand Doshi0dc79f42015-04-06 12:59:34 +0530374 'txt': "%{0}%".format(txt),
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530375 "start": start,
376 "page_len": page_len
377 }
378
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530379 having_clause = "having sum(sle.actual_qty) > 0"
380 if filters.get("is_return"):
381 having_clause = ""
382
Deepesh Garga0d192e2020-09-22 13:54:07 +0530383 meta = frappe.get_meta("Batch", cached=True)
384 searchfields = meta.get_search_fields()
385
386 search_columns = ''
Deepesh Gargf58a5ec2020-10-05 13:55:53 +0530387 search_cond = ''
388
Deepesh Garga0d192e2020-09-22 13:54:07 +0530389 if searchfields:
390 search_columns = ", " + ", ".join(searchfields)
Deepesh Garg1fae7742020-10-05 12:38:54 +0530391 search_cond = " or " + " or ".join([field + " like %(txt)s" for field in searchfields])
Deepesh Garga0d192e2020-09-22 13:54:07 +0530392
Anand Doshi0dc79f42015-04-06 12:59:34 +0530393 if args.get('warehouse'):
Deepesh Garga0d192e2020-09-22 13:54:07 +0530394 searchfields = ['batch.' + field for field in searchfields]
395 if searchfields:
396 search_columns = ", " + ", ".join(searchfields)
Deepesh Garg1fae7742020-10-05 12:38:54 +0530397 search_cond = " or " + " or ".join([field + " like %(txt)s" for field in searchfields])
Deepesh Garga0d192e2020-09-22 13:54:07 +0530398
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530399 batch_nos = frappe.db.sql("""select sle.batch_no, round(sum(sle.actual_qty),2), sle.stock_uom,
400 concat('MFG-',batch.manufacturing_date), concat('EXP-',batch.expiry_date)
Deepesh Garga0d192e2020-09-22 13:54:07 +0530401 {search_columns}
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530402 from `tabStock Ledger Entry` sle
403 INNER JOIN `tabBatch` batch on sle.batch_no = batch.name
404 where
405 batch.disabled = 0
406 and sle.item_code = %(item_code)s
407 and sle.warehouse = %(warehouse)s
408 and (sle.batch_no like %(txt)s
Sun Howwrongbum088be372019-12-24 12:29:25 +0530409 or batch.expiry_date like %(txt)s
Deepesh Gargf58a5ec2020-10-05 13:55:53 +0530410 or batch.manufacturing_date like %(txt)s
411 {search_cond})
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530412 and batch.docstatus < 2
413 {cond}
414 {match_conditions}
415 group by batch_no {having_clause}
416 order by batch.expiry_date, sle.batch_no desc
417 limit %(start)s, %(page_len)s""".format(
Deepesh Garga0d192e2020-09-22 13:54:07 +0530418 search_columns = search_columns,
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530419 cond=cond,
420 match_conditions=get_match_cond(doctype),
Deepesh Garg1fae7742020-10-05 12:38:54 +0530421 having_clause = having_clause,
422 search_cond = search_cond
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530423 ), args)
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530424
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530425 return batch_nos
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530426 else:
Deepesh Garga0d192e2020-09-22 13:54:07 +0530427 return frappe.db.sql("""select name, concat('MFG-', manufacturing_date), concat('EXP-',expiry_date)
428 {search_columns}
429 from `tabBatch` batch
Doridel Cahanap59e4c322018-08-06 17:15:18 +0800430 where batch.disabled = 0
431 and item = %(item_code)s
sivankar621740e2018-02-12 14:33:40 +0530432 and (name like %(txt)s
Sun Howwrongbum088be372019-12-24 12:29:25 +0530433 or expiry_date like %(txt)s
Deepesh Gargf58a5ec2020-10-05 13:55:53 +0530434 or manufacturing_date like %(txt)s
435 {search_cond})
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530436 and docstatus < 2
Neil Trini Lasradoebb60f52015-07-08 14:36:09 +0530437 {0}
Anand Doshi0dc79f42015-04-06 12:59:34 +0530438 {match_conditions}
Deepesh Gargf58a5ec2020-10-05 13:55:53 +0530439
Anand Doshi0dc79f42015-04-06 12:59:34 +0530440 order by expiry_date, name desc
Deepesh Garg1fae7742020-10-05 12:38:54 +0530441 limit %(start)s, %(page_len)s""".format(cond, search_columns = search_columns,
442 search_cond = search_cond, match_conditions=get_match_cond(doctype)), args)
Nabin Haitea4aa042014-05-28 12:56:28 +0530443
Himanshud94a38e2020-05-18 14:26:26 +0530444
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530445@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530446@frappe.validate_and_sanitize_search_inputs
Nabin Haitea4aa042014-05-28 12:56:28 +0530447def get_account_list(doctype, txt, searchfield, start, page_len, filters):
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530448 filter_list = []
Nabin Haitea4aa042014-05-28 12:56:28 +0530449
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530450 if isinstance(filters, dict):
451 for key, val in filters.items():
452 if isinstance(val, (list, tuple)):
453 filter_list.append([doctype, key, val[0], val[1]])
454 else:
455 filter_list.append([doctype, key, "=", val])
bhupeshg2e2e973f2015-04-14 22:15:24 +0530456 elif isinstance(filters, list):
457 filter_list.extend(filters)
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530458
Rushabh Mehta38c6b522015-04-23 13:14:17 +0530459 if "is_group" not in [d[1] for d in filter_list]:
460 filter_list.append(["Account", "is_group", "=", "0"])
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530461
462 if searchfield and txt:
463 filter_list.append([doctype, searchfield, "like", "%%%s%%" % txt])
464
Rushabh Mehtac0bb4532014-09-09 16:15:35 +0530465 return frappe.desk.reportview.execute("Account", filters = filter_list,
Nabin Haitea4aa042014-05-28 12:56:28 +0530466 fields = ["name", "parent_account"],
467 limit_start=start, limit_page_length=page_len, as_list=True)
Anand Doshifaefeaa2014-06-24 18:53:04 +0530468
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530469@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530470@frappe.validate_and_sanitize_search_inputs
Marica299e2172020-04-28 13:00:04 +0530471def get_blanket_orders(doctype, txt, searchfield, start, page_len, filters):
472 return frappe.db.sql("""select distinct bo.name, bo.blanket_order_type, bo.to_date
473 from `tabBlanket Order` bo, `tabBlanket Order Item` boi
474 where
475 boi.parent = bo.name
476 and boi.item_code = {item_code}
477 and bo.blanket_order_type = '{blanket_order_type}'
478 and bo.company = {company}
479 and bo.docstatus = 1"""
480 .format(item_code = frappe.db.escape(filters.get("item")),
481 blanket_order_type = filters.get("blanket_order_type"),
482 company = frappe.db.escape(filters.get("company"))
483 ))
Nabin Haitafd14f62015-10-19 11:55:28 +0530484
Himanshud94a38e2020-05-18 14:26:26 +0530485
Nabin Haitafd14f62015-10-19 11:55:28 +0530486@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530487@frappe.validate_and_sanitize_search_inputs
Nabin Haitafd14f62015-10-19 11:55:28 +0530488def get_income_account(doctype, txt, searchfield, start, page_len, filters):
489 from erpnext.controllers.queries import get_match_cond
490
491 # income account can be any Credit account,
492 # but can also be a Asset account with account_type='Income Account' in special circumstances.
493 # Hence the first condition is an "OR"
494 if not filters: filters = {}
495
Anand Doshi21e09a22015-10-29 12:21:41 +0530496 condition = ""
Nabin Haitafd14f62015-10-19 11:55:28 +0530497 if filters.get("company"):
498 condition += "and tabAccount.company = %(company)s"
Anand Doshi21e09a22015-10-29 12:21:41 +0530499
Nabin Haitafd14f62015-10-19 11:55:28 +0530500 return frappe.db.sql("""select tabAccount.name from `tabAccount`
501 where (tabAccount.report_type = "Profit and Loss"
502 or tabAccount.account_type in ("Income Account", "Temporary"))
503 and tabAccount.is_group=0
504 and tabAccount.`{key}` LIKE %(txt)s
Rushabh Mehta3574b372016-03-11 14:33:04 +0530505 {condition} {match_condition}
506 order by idx desc, name"""
Nabin Haitafd14f62015-10-19 11:55:28 +0530507 .format(condition=condition, match_condition=get_match_cond(doctype), key=searchfield), {
Suraj Shetty4b404c42018-09-27 15:39:34 +0530508 'txt': '%' + txt + '%',
Nabin Haitafd14f62015-10-19 11:55:28 +0530509 'company': filters.get("company", "")
Anand Doshi21e09a22015-10-29 12:21:41 +0530510 })
Nabin Hait3a15c922016-03-04 12:30:46 +0530511
Deepesh Garg96e874b2020-11-15 22:43:01 +0530512@frappe.whitelist()
513@frappe.validate_and_sanitize_search_inputs
514def get_filtered_dimensions(doctype, txt, searchfield, start, page_len, filters):
515 from erpnext.accounts.doctype.accounting_dimension_filter.accounting_dimension_filter import get_dimension_filter_map
516 dimension_filters = get_dimension_filter_map()
517 dimension_filters = dimension_filters.get((filters.get('dimension'),filters.get('account')))
Deepesh Garg6c17b842020-11-25 13:42:16 +0530518 query_filters = []
Deepesh Garg96e874b2020-11-15 22:43:01 +0530519
520 meta = frappe.get_meta(doctype)
Deepesh Garg96e874b2020-11-15 22:43:01 +0530521 if meta.is_tree:
Deepesh Garg6c17b842020-11-25 13:42:16 +0530522 query_filters.append(['is_group', '=', 0])
Deepesh Garg96e874b2020-11-15 22:43:01 +0530523
524 if meta.has_field('company'):
Deepesh Garg6c17b842020-11-25 13:42:16 +0530525 query_filters.append(['company', '=', filters.get('company')])
526
527 if txt:
528 query_filters.append([searchfield, 'LIKE', "%%%s%%" % txt])
Deepesh Garg96e874b2020-11-15 22:43:01 +0530529
530 if dimension_filters:
531 if dimension_filters['allow_or_restrict'] == 'Allow':
532 query_selector = 'in'
533 else:
534 query_selector = 'not in'
535
536 if len(dimension_filters['allowed_dimensions']) == 1:
537 dimensions = tuple(dimension_filters['allowed_dimensions'] * 2)
538 else:
539 dimensions = tuple(dimension_filters['allowed_dimensions'])
540
Deepesh Garg6c17b842020-11-25 13:42:16 +0530541 query_filters.append(['name', query_selector, dimensions])
Deepesh Garg96e874b2020-11-15 22:43:01 +0530542
Deepesh Garg6c17b842020-11-25 13:42:16 +0530543 output = frappe.get_all(doctype, filters=query_filters)
544 result = [d.name for d in output]
545
546 return [(d,) for d in set(result)]
Nabin Hait3a15c922016-03-04 12:30:46 +0530547
548@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530549@frappe.validate_and_sanitize_search_inputs
Nabin Hait3a15c922016-03-04 12:30:46 +0530550def get_expense_account(doctype, txt, searchfield, start, page_len, filters):
551 from erpnext.controllers.queries import get_match_cond
Rushabh Mehta203cc962016-04-07 15:25:43 +0530552
Nabin Hait3a15c922016-03-04 12:30:46 +0530553 if not filters: filters = {}
554
555 condition = ""
556 if filters.get("company"):
557 condition += "and tabAccount.company = %(company)s"
Rushabh Mehta203cc962016-04-07 15:25:43 +0530558
Nabin Hait3a15c922016-03-04 12:30:46 +0530559 return frappe.db.sql("""select tabAccount.name from `tabAccount`
560 where (tabAccount.report_type = "Profit and Loss"
Mangesh-Khairnar5619db22019-08-21 14:49:24 +0530561 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 +0530562 and tabAccount.is_group=0
563 and tabAccount.docstatus!=2
564 and tabAccount.{key} LIKE %(txt)s
565 {condition} {match_condition}"""
Suraj Shettybfc195d2018-09-21 10:20:52 +0530566 .format(condition=condition, key=searchfield,
Nabin Hait3a15c922016-03-04 12:30:46 +0530567 match_condition=get_match_cond(doctype)), {
Neil Trini Lasrado30b97b02016-03-31 23:10:13 +0530568 'company': filters.get("company", ""),
Suraj Shetty4b404c42018-09-27 15:39:34 +0530569 'txt': '%' + txt + '%'
Maxwell Morais35572612016-07-21 23:42:59 -0300570 })
suyashphadtare049a88c2017-01-12 17:49:37 +0530571
572
573@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530574@frappe.validate_and_sanitize_search_inputs
suyashphadtare049a88c2017-01-12 17:49:37 +0530575def warehouse_query(doctype, txt, searchfield, start, page_len, filters):
576 # Should be used when item code is passed in filters.
suyashphadtare750a0672017-01-18 15:35:01 +0530577 conditions, bin_conditions = [], []
578 filter_dict = get_doctype_wise_filters(filters)
579
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530580 query = """select `tabWarehouse`.name,
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530581 CONCAT_WS(" : ", "Actual Qty", ifnull(round(`tabBin`.actual_qty, 2), 0 )) actual_qty
582 from `tabWarehouse` left join `tabBin`
583 on `tabBin`.warehouse = `tabWarehouse`.name {bin_conditions}
suyashphadtare34ab1362017-01-31 15:14:44 +0530584 where
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530585 `tabWarehouse`.`{key}` like {txt}
suyashphadtare34ab1362017-01-31 15:14:44 +0530586 {fcond} {mcond}
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530587 order by ifnull(`tabBin`.actual_qty, 0) desc
suyashphadtare34ab1362017-01-31 15:14:44 +0530588 limit
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530589 {start}, {page_len}
suyashphadtare34ab1362017-01-31 15:14:44 +0530590 """.format(
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530591 bin_conditions=get_filters_cond(doctype, filter_dict.get("Bin"),bin_conditions, ignore_permissions=True),
Suraj Shettybfc195d2018-09-21 10:20:52 +0530592 key=searchfield,
suyashphadtare34ab1362017-01-31 15:14:44 +0530593 fcond=get_filters_cond(doctype, filter_dict.get("Warehouse"), conditions),
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530594 mcond=get_match_cond(doctype),
595 start=start,
596 page_len=page_len,
597 txt=frappe.db.escape('%{0}%'.format(txt))
598 )
599
600 return frappe.db.sql(query)
suyashphadtare750a0672017-01-18 15:35:01 +0530601
602
603def get_doctype_wise_filters(filters):
604 # Helper function to seperate filters doctype_wise
605 filter_dict = defaultdict(list)
606 for row in filters:
607 filter_dict[row[0]].append(row)
608 return filter_dict
tundebabzy2a4fefc2017-11-29 06:23:09 +0100609
610
611@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530612@frappe.validate_and_sanitize_search_inputs
tundebabzy2a4fefc2017-11-29 06:23:09 +0100613def get_batch_numbers(doctype, txt, searchfield, start, page_len, filters):
rohitwaghchaure9fbed562018-01-12 16:22:33 +0530614 query = """select batch_id from `tabBatch`
Doridel Cahanap59e4c322018-08-06 17:15:18 +0800615 where disabled = 0
616 and (expiry_date >= CURDATE() or expiry_date IS NULL)
Suraj Shettybfc195d2018-09-21 10:20:52 +0530617 and name like {txt}""".format(txt = frappe.db.escape('%{0}%'.format(txt)))
tundebabzy2a4fefc2017-11-29 06:23:09 +0100618
rohitwaghchaure9fbed562018-01-12 16:22:33 +0530619 if filters and filters.get('item'):
Suraj Shettybfc195d2018-09-21 10:20:52 +0530620 query += " and item = {item}".format(item = frappe.db.escape(filters.get('item')))
tundebabzy2a4fefc2017-11-29 06:23:09 +0100621
Sachin Mane64f48db2018-01-08 17:57:32 +0530622 return frappe.db.sql(query, filters)
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530623
Himanshud94a38e2020-05-18 14:26:26 +0530624
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530625@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530626@frappe.validate_and_sanitize_search_inputs
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530627def item_manufacturer_query(doctype, txt, searchfield, start, page_len, filters):
Maricabac4b932019-09-16 19:44:28 +0530628 item_filters = [
629 ['manufacturer', 'like', '%' + txt + '%'],
630 ['item_code', '=', filters.get("item_code")]
631 ]
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530632
Maricabac4b932019-09-16 19:44:28 +0530633 item_manufacturers = frappe.get_all(
634 "Item Manufacturer",
635 fields=["manufacturer", "manufacturer_part_no"],
636 filters=item_filters,
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530637 limit_start=start,
638 limit_page_length=page_len,
639 as_list=1
640 )
Maricabac4b932019-09-16 19:44:28 +0530641 return item_manufacturers
Saqibd9956092019-11-18 11:46:55 +0530642
Himanshud94a38e2020-05-18 14:26:26 +0530643
Saqibd9956092019-11-18 11:46:55 +0530644@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530645@frappe.validate_and_sanitize_search_inputs
Saqibd9956092019-11-18 11:46:55 +0530646def get_purchase_receipts(doctype, txt, searchfield, start, page_len, filters):
647 query = """
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530648 select pr.name
Saqibd9956092019-11-18 11:46:55 +0530649 from `tabPurchase Receipt` pr, `tabPurchase Receipt Item` pritem
650 where pr.docstatus = 1 and pritem.parent = pr.name
651 and pr.name like {txt}""".format(txt = frappe.db.escape('%{0}%'.format(txt)))
652
653 if filters and filters.get('item_code'):
654 query += " and pritem.item_code = {item_code}".format(item_code = frappe.db.escape(filters.get('item_code')))
655
656 return frappe.db.sql(query, filters)
657
Himanshud94a38e2020-05-18 14:26:26 +0530658
Saqibd9956092019-11-18 11:46:55 +0530659@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530660@frappe.validate_and_sanitize_search_inputs
Saqibd9956092019-11-18 11:46:55 +0530661def get_purchase_invoices(doctype, txt, searchfield, start, page_len, filters):
662 query = """
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530663 select pi.name
Saqibd9956092019-11-18 11:46:55 +0530664 from `tabPurchase Invoice` pi, `tabPurchase Invoice Item` piitem
665 where pi.docstatus = 1 and piitem.parent = pi.name
666 and pi.name like {txt}""".format(txt = frappe.db.escape('%{0}%'.format(txt)))
667
668 if filters and filters.get('item_code'):
669 query += " and piitem.item_code = {item_code}".format(item_code = frappe.db.escape(filters.get('item_code')))
670
671 return frappe.db.sql(query, filters)
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530672
Himanshud94a38e2020-05-18 14:26:26 +0530673
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530674@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530675@frappe.validate_and_sanitize_search_inputs
Rucha Mahabal20e53152021-01-18 14:56:55 +0530676def get_healthcare_service_units(doctype, txt, searchfield, start, page_len, filters):
677 query = """
678 select name
679 from `tabHealthcare Service Unit`
680 where
681 is_group = 0
682 and company = {company}
683 and name like {txt}""".format(
684 company = frappe.db.escape(filters.get('company')), txt = frappe.db.escape('%{0}%'.format(txt)))
685
686 if filters and filters.get('inpatient_record'):
687 from erpnext.healthcare.doctype.inpatient_medication_entry.inpatient_medication_entry import get_current_healthcare_service_unit
688 service_unit = get_current_healthcare_service_unit(filters.get('inpatient_record'))
689
690 # if the patient is admitted, then appointments should be allowed against the admission service unit,
691 # inspite of it being an Inpatient Occupancy service unit
692 if service_unit:
693 query += " and (allow_appointments = 1 or name = {service_unit})".format(service_unit = frappe.db.escape(service_unit))
694 else:
695 query += " and allow_appointments = 1"
696 else:
697 query += " and allow_appointments = 1"
698
699 return frappe.db.sql(query, filters)
700
701
702@frappe.whitelist()
703@frappe.validate_and_sanitize_search_inputs
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530704def get_tax_template(doctype, txt, searchfield, start, page_len, filters):
705
706 item_doc = frappe.get_cached_doc('Item', filters.get('item_code'))
707 item_group = filters.get('item_group')
708 taxes = item_doc.taxes or []
709
710 while item_group:
711 item_group_doc = frappe.get_cached_doc('Item Group', item_group)
712 taxes += item_group_doc.taxes or []
713 item_group = item_group_doc.parent_item_group
714
715 if not taxes:
716 return frappe.db.sql(""" SELECT name FROM `tabItem Tax Template` """)
717 else:
Marica0fcb05a2020-08-10 14:48:13 +0530718 valid_from = filters.get('valid_from')
719 valid_from = valid_from[1] if isinstance(valid_from, list) else valid_from
720
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530721 args = {
722 'item_code': filters.get('item_code'),
Marica0fcb05a2020-08-10 14:48:13 +0530723 'posting_date': valid_from,
mohammadahmad199041c0c9f2020-06-18 11:18:44 +0500724 'tax_category': filters.get('tax_category'),
725 'company': filters.get('company')
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530726 }
727
728 taxes = _get_item_tax_template(args, taxes, for_validate=True)
729 return [(d,) for d in set(taxes)]
Himanshud94a38e2020-05-18 14:26:26 +0530730
731
Ankush Menat7eac4a22021-04-19 10:33:39 +0530732def get_fields(doctype, fields=None):
733 if fields is None:
734 fields = []
Himanshud94a38e2020-05-18 14:26:26 +0530735 meta = frappe.get_meta(doctype)
736 fields.extend(meta.get_search_fields())
737
738 if meta.title_field and not meta.title_field.strip() in fields:
739 fields.insert(1, meta.title_field.strip())
740
741 return unique(fields)