blob: 8fe3816c24a26bac0779644225bfaaca95dfb76c [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
Himanshud94a38e2020-05-18 14:26:26 +0530295 fields = get_fields("Project", ["name"])
296
297 return frappe.db.sql("""select {fields} from `tabProject`
Anand Doshibd67e872014-04-11 16:51:27 +0530298 where `tabProject`.status not in ("Completed", "Cancelled")
Rushabh Mehta3574b372016-03-11 14:33:04 +0530299 and {cond} `tabProject`.name like %(txt)s {match_cond}
300 order by
301 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
302 idx desc,
303 `tabProject`.name asc
304 limit {start}, {page_len}""".format(
Himanshud94a38e2020-05-18 14:26:26 +0530305 fields=", ".join(['`tabProject`.{0}'.format(f) for f in fields]),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530306 cond=cond,
307 match_cond=get_match_cond(doctype),
308 start=start,
309 page_len=page_len), {
310 "txt": "%{0}%".format(txt),
Nabin Haitdf4deba2016-03-16 11:16:31 +0530311 "_txt": txt.replace('%', '')
Rushabh Mehta3574b372016-03-11 14:33:04 +0530312 })
Anand Doshibd67e872014-04-11 16:51:27 +0530313
tundebabzyf6d738b2017-09-18 12:40:09 +0100314
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530315@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530316@frappe.validate_and_sanitize_search_inputs
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530317def get_delivery_notes_to_be_billed(doctype, txt, searchfield, start, page_len, filters, as_dict):
Himanshud94a38e2020-05-18 14:26:26 +0530318 fields = get_fields("Delivery Note", ["name", "customer", "posting_date"])
319
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530320 return frappe.db.sql("""
Himanshud94a38e2020-05-18 14:26:26 +0530321 select %(fields)s
Anand Doshibd67e872014-04-11 16:51:27 +0530322 from `tabDelivery Note`
323 where `tabDelivery Note`.`%(key)s` like %(txt)s and
tundebabzyf6d738b2017-09-18 12:40:09 +0100324 `tabDelivery Note`.docstatus = 1
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530325 and status not in ("Stopped", "Closed") %(fcond)s
tundebabzyf6d738b2017-09-18 12:40:09 +0100326 and (
327 (`tabDelivery Note`.is_return = 0 and `tabDelivery Note`.per_billed < 100)
328 or `tabDelivery Note`.grand_total = 0
329 or (
330 `tabDelivery Note`.is_return = 1
331 and return_against in (select name from `tabDelivery Note` where per_billed < 100)
332 )
333 )
rohitwaghchaured07a3e12019-05-15 07:46:28 +0530334 %(mcond)s order by `tabDelivery Note`.`%(key)s` asc limit %(start)s, %(page_len)s
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530335 """ % {
Himanshud94a38e2020-05-18 14:26:26 +0530336 "fields": ", ".join(["`tabDelivery Note`.{0}".format(f) for f in fields]),
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530337 "key": searchfield,
338 "fcond": get_filters_cond(doctype, filters, []),
339 "mcond": get_match_cond(doctype),
rohitwaghchaured07a3e12019-05-15 07:46:28 +0530340 "start": start,
341 "page_len": page_len,
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530342 "txt": "%(txt)s"
tundebabzyf6d738b2017-09-18 12:40:09 +0100343 }, {"txt": ("%%%s%%" % txt)}, as_dict=as_dict)
344
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530345
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530346@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530347@frappe.validate_and_sanitize_search_inputs
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530348def get_batch_no(doctype, txt, searchfield, start, page_len, filters):
Neil Trini Lasradoebb60f52015-07-08 14:36:09 +0530349 cond = ""
350 if filters.get("posting_date"):
Nabin Hait7918b922018-01-31 15:30:03 +0530351 cond = "and (batch.expiry_date is null or batch.expiry_date >= %(posting_date)s)"
Rushabh Mehtab6398be2015-08-26 10:50:16 +0530352
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530353 batch_nos = None
354 args = {
355 'item_code': filters.get("item_code"),
356 'warehouse': filters.get("warehouse"),
357 'posting_date': filters.get('posting_date'),
Anand Doshi0dc79f42015-04-06 12:59:34 +0530358 'txt': "%{0}%".format(txt),
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530359 "start": start,
360 "page_len": page_len
361 }
362
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530363 having_clause = "having sum(sle.actual_qty) > 0"
364 if filters.get("is_return"):
365 having_clause = ""
366
Deepesh Garga0d192e2020-09-22 13:54:07 +0530367 meta = frappe.get_meta("Batch", cached=True)
368 searchfields = meta.get_search_fields()
369
370 search_columns = ''
Deepesh Gargf58a5ec2020-10-05 13:55:53 +0530371 search_cond = ''
372
Deepesh Garga0d192e2020-09-22 13:54:07 +0530373 if searchfields:
374 search_columns = ", " + ", ".join(searchfields)
Deepesh Garg1fae7742020-10-05 12:38:54 +0530375 search_cond = " or " + " or ".join([field + " like %(txt)s" for field in searchfields])
Deepesh Garga0d192e2020-09-22 13:54:07 +0530376
Anand Doshi0dc79f42015-04-06 12:59:34 +0530377 if args.get('warehouse'):
Deepesh Garga0d192e2020-09-22 13:54:07 +0530378 searchfields = ['batch.' + field for field in searchfields]
379 if searchfields:
380 search_columns = ", " + ", ".join(searchfields)
Deepesh Garg1fae7742020-10-05 12:38:54 +0530381 search_cond = " or " + " or ".join([field + " like %(txt)s" for field in searchfields])
Deepesh Garga0d192e2020-09-22 13:54:07 +0530382
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530383 batch_nos = frappe.db.sql("""select sle.batch_no, round(sum(sle.actual_qty),2), sle.stock_uom,
384 concat('MFG-',batch.manufacturing_date), concat('EXP-',batch.expiry_date)
Deepesh Garga0d192e2020-09-22 13:54:07 +0530385 {search_columns}
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530386 from `tabStock Ledger Entry` sle
387 INNER JOIN `tabBatch` batch on sle.batch_no = batch.name
388 where
389 batch.disabled = 0
390 and sle.item_code = %(item_code)s
391 and sle.warehouse = %(warehouse)s
392 and (sle.batch_no like %(txt)s
Sun Howwrongbum088be372019-12-24 12:29:25 +0530393 or batch.expiry_date like %(txt)s
Deepesh Gargf58a5ec2020-10-05 13:55:53 +0530394 or batch.manufacturing_date like %(txt)s
395 {search_cond})
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530396 and batch.docstatus < 2
397 {cond}
398 {match_conditions}
399 group by batch_no {having_clause}
400 order by batch.expiry_date, sle.batch_no desc
401 limit %(start)s, %(page_len)s""".format(
Deepesh Garga0d192e2020-09-22 13:54:07 +0530402 search_columns = search_columns,
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530403 cond=cond,
404 match_conditions=get_match_cond(doctype),
Deepesh Garg1fae7742020-10-05 12:38:54 +0530405 having_clause = having_clause,
406 search_cond = search_cond
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530407 ), args)
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530408
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530409 return batch_nos
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530410 else:
Deepesh Garga0d192e2020-09-22 13:54:07 +0530411 return frappe.db.sql("""select name, concat('MFG-', manufacturing_date), concat('EXP-',expiry_date)
412 {search_columns}
413 from `tabBatch` batch
Doridel Cahanap59e4c322018-08-06 17:15:18 +0800414 where batch.disabled = 0
415 and item = %(item_code)s
sivankar621740e2018-02-12 14:33:40 +0530416 and (name like %(txt)s
Sun Howwrongbum088be372019-12-24 12:29:25 +0530417 or expiry_date like %(txt)s
Deepesh Gargf58a5ec2020-10-05 13:55:53 +0530418 or manufacturing_date like %(txt)s
419 {search_cond})
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530420 and docstatus < 2
Neil Trini Lasradoebb60f52015-07-08 14:36:09 +0530421 {0}
Anand Doshi0dc79f42015-04-06 12:59:34 +0530422 {match_conditions}
Deepesh Gargf58a5ec2020-10-05 13:55:53 +0530423
Anand Doshi0dc79f42015-04-06 12:59:34 +0530424 order by expiry_date, name desc
Deepesh Garg1fae7742020-10-05 12:38:54 +0530425 limit %(start)s, %(page_len)s""".format(cond, search_columns = search_columns,
426 search_cond = search_cond, match_conditions=get_match_cond(doctype)), args)
Nabin Haitea4aa042014-05-28 12:56:28 +0530427
Himanshud94a38e2020-05-18 14:26:26 +0530428
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530429@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530430@frappe.validate_and_sanitize_search_inputs
Nabin Haitea4aa042014-05-28 12:56:28 +0530431def get_account_list(doctype, txt, searchfield, start, page_len, filters):
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530432 filter_list = []
Nabin Haitea4aa042014-05-28 12:56:28 +0530433
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530434 if isinstance(filters, dict):
435 for key, val in filters.items():
436 if isinstance(val, (list, tuple)):
437 filter_list.append([doctype, key, val[0], val[1]])
438 else:
439 filter_list.append([doctype, key, "=", val])
bhupeshg2e2e973f2015-04-14 22:15:24 +0530440 elif isinstance(filters, list):
441 filter_list.extend(filters)
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530442
Rushabh Mehta38c6b522015-04-23 13:14:17 +0530443 if "is_group" not in [d[1] for d in filter_list]:
444 filter_list.append(["Account", "is_group", "=", "0"])
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530445
446 if searchfield and txt:
447 filter_list.append([doctype, searchfield, "like", "%%%s%%" % txt])
448
Rushabh Mehtac0bb4532014-09-09 16:15:35 +0530449 return frappe.desk.reportview.execute("Account", filters = filter_list,
Nabin Haitea4aa042014-05-28 12:56:28 +0530450 fields = ["name", "parent_account"],
451 limit_start=start, limit_page_length=page_len, as_list=True)
Anand Doshifaefeaa2014-06-24 18:53:04 +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
Marica299e2172020-04-28 13:00:04 +0530455def get_blanket_orders(doctype, txt, searchfield, start, page_len, filters):
456 return frappe.db.sql("""select distinct bo.name, bo.blanket_order_type, bo.to_date
457 from `tabBlanket Order` bo, `tabBlanket Order Item` boi
458 where
459 boi.parent = bo.name
460 and boi.item_code = {item_code}
461 and bo.blanket_order_type = '{blanket_order_type}'
462 and bo.company = {company}
463 and bo.docstatus = 1"""
464 .format(item_code = frappe.db.escape(filters.get("item")),
465 blanket_order_type = filters.get("blanket_order_type"),
466 company = frappe.db.escape(filters.get("company"))
467 ))
Nabin Haitafd14f62015-10-19 11:55:28 +0530468
Himanshud94a38e2020-05-18 14:26:26 +0530469
Nabin Haitafd14f62015-10-19 11:55:28 +0530470@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530471@frappe.validate_and_sanitize_search_inputs
Nabin Haitafd14f62015-10-19 11:55:28 +0530472def get_income_account(doctype, txt, searchfield, start, page_len, filters):
473 from erpnext.controllers.queries import get_match_cond
474
475 # income account can be any Credit account,
476 # but can also be a Asset account with account_type='Income Account' in special circumstances.
477 # Hence the first condition is an "OR"
478 if not filters: filters = {}
479
Anand Doshi21e09a22015-10-29 12:21:41 +0530480 condition = ""
Nabin Haitafd14f62015-10-19 11:55:28 +0530481 if filters.get("company"):
482 condition += "and tabAccount.company = %(company)s"
Anand Doshi21e09a22015-10-29 12:21:41 +0530483
Nabin Haitafd14f62015-10-19 11:55:28 +0530484 return frappe.db.sql("""select tabAccount.name from `tabAccount`
485 where (tabAccount.report_type = "Profit and Loss"
486 or tabAccount.account_type in ("Income Account", "Temporary"))
487 and tabAccount.is_group=0
488 and tabAccount.`{key}` LIKE %(txt)s
Rushabh Mehta3574b372016-03-11 14:33:04 +0530489 {condition} {match_condition}
490 order by idx desc, name"""
Nabin Haitafd14f62015-10-19 11:55:28 +0530491 .format(condition=condition, match_condition=get_match_cond(doctype), key=searchfield), {
Suraj Shetty4b404c42018-09-27 15:39:34 +0530492 'txt': '%' + txt + '%',
Nabin Haitafd14f62015-10-19 11:55:28 +0530493 'company': filters.get("company", "")
Anand Doshi21e09a22015-10-29 12:21:41 +0530494 })
Nabin Hait3a15c922016-03-04 12:30:46 +0530495
496
497@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530498@frappe.validate_and_sanitize_search_inputs
Nabin Hait3a15c922016-03-04 12:30:46 +0530499def get_expense_account(doctype, txt, searchfield, start, page_len, filters):
500 from erpnext.controllers.queries import get_match_cond
Rushabh Mehta203cc962016-04-07 15:25:43 +0530501
Nabin Hait3a15c922016-03-04 12:30:46 +0530502 if not filters: filters = {}
503
504 condition = ""
505 if filters.get("company"):
506 condition += "and tabAccount.company = %(company)s"
Rushabh Mehta203cc962016-04-07 15:25:43 +0530507
Nabin Hait3a15c922016-03-04 12:30:46 +0530508 return frappe.db.sql("""select tabAccount.name from `tabAccount`
509 where (tabAccount.report_type = "Profit and Loss"
Mangesh-Khairnar5619db22019-08-21 14:49:24 +0530510 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 +0530511 and tabAccount.is_group=0
512 and tabAccount.docstatus!=2
513 and tabAccount.{key} LIKE %(txt)s
514 {condition} {match_condition}"""
Suraj Shettybfc195d2018-09-21 10:20:52 +0530515 .format(condition=condition, key=searchfield,
Nabin Hait3a15c922016-03-04 12:30:46 +0530516 match_condition=get_match_cond(doctype)), {
Neil Trini Lasrado30b97b02016-03-31 23:10:13 +0530517 'company': filters.get("company", ""),
Suraj Shetty4b404c42018-09-27 15:39:34 +0530518 'txt': '%' + txt + '%'
Maxwell Morais35572612016-07-21 23:42:59 -0300519 })
suyashphadtare049a88c2017-01-12 17:49:37 +0530520
521
522@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530523@frappe.validate_and_sanitize_search_inputs
suyashphadtare049a88c2017-01-12 17:49:37 +0530524def warehouse_query(doctype, txt, searchfield, start, page_len, filters):
525 # Should be used when item code is passed in filters.
suyashphadtare750a0672017-01-18 15:35:01 +0530526 conditions, bin_conditions = [], []
527 filter_dict = get_doctype_wise_filters(filters)
528
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530529 query = """select `tabWarehouse`.name,
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530530 CONCAT_WS(" : ", "Actual Qty", ifnull(round(`tabBin`.actual_qty, 2), 0 )) actual_qty
531 from `tabWarehouse` left join `tabBin`
532 on `tabBin`.warehouse = `tabWarehouse`.name {bin_conditions}
suyashphadtare34ab1362017-01-31 15:14:44 +0530533 where
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530534 `tabWarehouse`.`{key}` like {txt}
suyashphadtare34ab1362017-01-31 15:14:44 +0530535 {fcond} {mcond}
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530536 order by ifnull(`tabBin`.actual_qty, 0) desc
suyashphadtare34ab1362017-01-31 15:14:44 +0530537 limit
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530538 {start}, {page_len}
suyashphadtare34ab1362017-01-31 15:14:44 +0530539 """.format(
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530540 bin_conditions=get_filters_cond(doctype, filter_dict.get("Bin"),bin_conditions, ignore_permissions=True),
Suraj Shettybfc195d2018-09-21 10:20:52 +0530541 key=searchfield,
suyashphadtare34ab1362017-01-31 15:14:44 +0530542 fcond=get_filters_cond(doctype, filter_dict.get("Warehouse"), conditions),
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530543 mcond=get_match_cond(doctype),
544 start=start,
545 page_len=page_len,
546 txt=frappe.db.escape('%{0}%'.format(txt))
547 )
548
549 return frappe.db.sql(query)
suyashphadtare750a0672017-01-18 15:35:01 +0530550
551
552def get_doctype_wise_filters(filters):
553 # Helper function to seperate filters doctype_wise
554 filter_dict = defaultdict(list)
555 for row in filters:
556 filter_dict[row[0]].append(row)
557 return filter_dict
tundebabzy2a4fefc2017-11-29 06:23:09 +0100558
559
560@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530561@frappe.validate_and_sanitize_search_inputs
tundebabzy2a4fefc2017-11-29 06:23:09 +0100562def get_batch_numbers(doctype, txt, searchfield, start, page_len, filters):
rohitwaghchaure9fbed562018-01-12 16:22:33 +0530563 query = """select batch_id from `tabBatch`
Doridel Cahanap59e4c322018-08-06 17:15:18 +0800564 where disabled = 0
565 and (expiry_date >= CURDATE() or expiry_date IS NULL)
Suraj Shettybfc195d2018-09-21 10:20:52 +0530566 and name like {txt}""".format(txt = frappe.db.escape('%{0}%'.format(txt)))
tundebabzy2a4fefc2017-11-29 06:23:09 +0100567
rohitwaghchaure9fbed562018-01-12 16:22:33 +0530568 if filters and filters.get('item'):
Suraj Shettybfc195d2018-09-21 10:20:52 +0530569 query += " and item = {item}".format(item = frappe.db.escape(filters.get('item')))
tundebabzy2a4fefc2017-11-29 06:23:09 +0100570
Sachin Mane64f48db2018-01-08 17:57:32 +0530571 return frappe.db.sql(query, filters)
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530572
Himanshud94a38e2020-05-18 14:26:26 +0530573
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530574@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530575@frappe.validate_and_sanitize_search_inputs
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530576def item_manufacturer_query(doctype, txt, searchfield, start, page_len, filters):
Maricabac4b932019-09-16 19:44:28 +0530577 item_filters = [
578 ['manufacturer', 'like', '%' + txt + '%'],
579 ['item_code', '=', filters.get("item_code")]
580 ]
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530581
Maricabac4b932019-09-16 19:44:28 +0530582 item_manufacturers = frappe.get_all(
583 "Item Manufacturer",
584 fields=["manufacturer", "manufacturer_part_no"],
585 filters=item_filters,
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530586 limit_start=start,
587 limit_page_length=page_len,
588 as_list=1
589 )
Maricabac4b932019-09-16 19:44:28 +0530590 return item_manufacturers
Saqibd9956092019-11-18 11:46:55 +0530591
Himanshud94a38e2020-05-18 14:26:26 +0530592
Saqibd9956092019-11-18 11:46:55 +0530593@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530594@frappe.validate_and_sanitize_search_inputs
Saqibd9956092019-11-18 11:46:55 +0530595def get_purchase_receipts(doctype, txt, searchfield, start, page_len, filters):
596 query = """
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530597 select pr.name
Saqibd9956092019-11-18 11:46:55 +0530598 from `tabPurchase Receipt` pr, `tabPurchase Receipt Item` pritem
599 where pr.docstatus = 1 and pritem.parent = pr.name
600 and pr.name like {txt}""".format(txt = frappe.db.escape('%{0}%'.format(txt)))
601
602 if filters and filters.get('item_code'):
603 query += " and pritem.item_code = {item_code}".format(item_code = frappe.db.escape(filters.get('item_code')))
604
605 return frappe.db.sql(query, filters)
606
Himanshud94a38e2020-05-18 14:26:26 +0530607
Saqibd9956092019-11-18 11:46:55 +0530608@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530609@frappe.validate_and_sanitize_search_inputs
Saqibd9956092019-11-18 11:46:55 +0530610def get_purchase_invoices(doctype, txt, searchfield, start, page_len, filters):
611 query = """
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530612 select pi.name
Saqibd9956092019-11-18 11:46:55 +0530613 from `tabPurchase Invoice` pi, `tabPurchase Invoice Item` piitem
614 where pi.docstatus = 1 and piitem.parent = pi.name
615 and pi.name like {txt}""".format(txt = frappe.db.escape('%{0}%'.format(txt)))
616
617 if filters and filters.get('item_code'):
618 query += " and piitem.item_code = {item_code}".format(item_code = frappe.db.escape(filters.get('item_code')))
619
620 return frappe.db.sql(query, filters)
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530621
Himanshud94a38e2020-05-18 14:26:26 +0530622
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530623@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530624@frappe.validate_and_sanitize_search_inputs
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530625def get_tax_template(doctype, txt, searchfield, start, page_len, filters):
626
627 item_doc = frappe.get_cached_doc('Item', filters.get('item_code'))
628 item_group = filters.get('item_group')
629 taxes = item_doc.taxes or []
630
631 while item_group:
632 item_group_doc = frappe.get_cached_doc('Item Group', item_group)
633 taxes += item_group_doc.taxes or []
634 item_group = item_group_doc.parent_item_group
635
636 if not taxes:
637 return frappe.db.sql(""" SELECT name FROM `tabItem Tax Template` """)
638 else:
Marica0fcb05a2020-08-10 14:48:13 +0530639 valid_from = filters.get('valid_from')
640 valid_from = valid_from[1] if isinstance(valid_from, list) else valid_from
641
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530642 args = {
643 'item_code': filters.get('item_code'),
Marica0fcb05a2020-08-10 14:48:13 +0530644 'posting_date': valid_from,
mohammadahmad199041c0c9f2020-06-18 11:18:44 +0500645 'tax_category': filters.get('tax_category'),
646 'company': filters.get('company')
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530647 }
648
649 taxes = _get_item_tax_template(args, taxes, for_validate=True)
650 return [(d,) for d in set(taxes)]
Himanshud94a38e2020-05-18 14:26:26 +0530651
652
653def get_fields(doctype, fields=[]):
654 meta = frappe.get_meta(doctype)
655 fields.extend(meta.get_search_fields())
656
657 if meta.title_field and not meta.title_field.strip() in fields:
658 fields.insert(1, meta.title_field.strip())
659
660 return unique(fields)