blob: 10ff6ad8d929f18b9afd6f4a0c3e5b37de55a3ec [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
Anand Doshi0dc79f42015-04-06 12:59:34 +0530367 if args.get('warehouse'):
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530368 batch_nos = frappe.db.sql("""select sle.batch_no, round(sum(sle.actual_qty),2), sle.stock_uom,
369 concat('MFG-',batch.manufacturing_date), concat('EXP-',batch.expiry_date)
370 from `tabStock Ledger Entry` sle
371 INNER JOIN `tabBatch` batch on sle.batch_no = batch.name
372 where
373 batch.disabled = 0
374 and sle.item_code = %(item_code)s
375 and sle.warehouse = %(warehouse)s
376 and (sle.batch_no like %(txt)s
Sun Howwrongbum088be372019-12-24 12:29:25 +0530377 or batch.expiry_date like %(txt)s
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530378 or batch.manufacturing_date like %(txt)s)
379 and batch.docstatus < 2
380 {cond}
381 {match_conditions}
382 group by batch_no {having_clause}
383 order by batch.expiry_date, sle.batch_no desc
384 limit %(start)s, %(page_len)s""".format(
385 cond=cond,
386 match_conditions=get_match_cond(doctype),
387 having_clause = having_clause
388 ), args)
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530389
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530390 return batch_nos
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530391 else:
sivankar621740e2018-02-12 14:33:40 +0530392 return frappe.db.sql("""select name, concat('MFG-', manufacturing_date), concat('EXP-',expiry_date) from `tabBatch` batch
Doridel Cahanap59e4c322018-08-06 17:15:18 +0800393 where batch.disabled = 0
394 and item = %(item_code)s
sivankar621740e2018-02-12 14:33:40 +0530395 and (name like %(txt)s
Sun Howwrongbum088be372019-12-24 12:29:25 +0530396 or expiry_date like %(txt)s
sivankar621740e2018-02-12 14:33:40 +0530397 or manufacturing_date like %(txt)s)
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530398 and docstatus < 2
Neil Trini Lasradoebb60f52015-07-08 14:36:09 +0530399 {0}
Anand Doshi0dc79f42015-04-06 12:59:34 +0530400 {match_conditions}
401 order by expiry_date, name desc
Nabin Haite52ee552015-09-02 10:55:32 +0530402 limit %(start)s, %(page_len)s""".format(cond, match_conditions=get_match_cond(doctype)), args)
Nabin Haitea4aa042014-05-28 12:56:28 +0530403
Himanshud94a38e2020-05-18 14:26:26 +0530404
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530405@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530406@frappe.validate_and_sanitize_search_inputs
Nabin Haitea4aa042014-05-28 12:56:28 +0530407def get_account_list(doctype, txt, searchfield, start, page_len, filters):
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530408 filter_list = []
Nabin Haitea4aa042014-05-28 12:56:28 +0530409
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530410 if isinstance(filters, dict):
411 for key, val in filters.items():
412 if isinstance(val, (list, tuple)):
413 filter_list.append([doctype, key, val[0], val[1]])
414 else:
415 filter_list.append([doctype, key, "=", val])
bhupeshg2e2e973f2015-04-14 22:15:24 +0530416 elif isinstance(filters, list):
417 filter_list.extend(filters)
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530418
Rushabh Mehta38c6b522015-04-23 13:14:17 +0530419 if "is_group" not in [d[1] for d in filter_list]:
420 filter_list.append(["Account", "is_group", "=", "0"])
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530421
422 if searchfield and txt:
423 filter_list.append([doctype, searchfield, "like", "%%%s%%" % txt])
424
Rushabh Mehtac0bb4532014-09-09 16:15:35 +0530425 return frappe.desk.reportview.execute("Account", filters = filter_list,
Nabin Haitea4aa042014-05-28 12:56:28 +0530426 fields = ["name", "parent_account"],
427 limit_start=start, limit_page_length=page_len, as_list=True)
Anand Doshifaefeaa2014-06-24 18:53:04 +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
Marica299e2172020-04-28 13:00:04 +0530431def get_blanket_orders(doctype, txt, searchfield, start, page_len, filters):
432 return frappe.db.sql("""select distinct bo.name, bo.blanket_order_type, bo.to_date
433 from `tabBlanket Order` bo, `tabBlanket Order Item` boi
434 where
435 boi.parent = bo.name
436 and boi.item_code = {item_code}
437 and bo.blanket_order_type = '{blanket_order_type}'
438 and bo.company = {company}
439 and bo.docstatus = 1"""
440 .format(item_code = frappe.db.escape(filters.get("item")),
441 blanket_order_type = filters.get("blanket_order_type"),
442 company = frappe.db.escape(filters.get("company"))
443 ))
Nabin Haitafd14f62015-10-19 11:55:28 +0530444
Himanshud94a38e2020-05-18 14:26:26 +0530445
Nabin Haitafd14f62015-10-19 11:55:28 +0530446@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530447@frappe.validate_and_sanitize_search_inputs
Nabin Haitafd14f62015-10-19 11:55:28 +0530448def get_income_account(doctype, txt, searchfield, start, page_len, filters):
449 from erpnext.controllers.queries import get_match_cond
450
451 # income account can be any Credit account,
452 # but can also be a Asset account with account_type='Income Account' in special circumstances.
453 # Hence the first condition is an "OR"
454 if not filters: filters = {}
455
Anand Doshi21e09a22015-10-29 12:21:41 +0530456 condition = ""
Nabin Haitafd14f62015-10-19 11:55:28 +0530457 if filters.get("company"):
458 condition += "and tabAccount.company = %(company)s"
Anand Doshi21e09a22015-10-29 12:21:41 +0530459
Nabin Haitafd14f62015-10-19 11:55:28 +0530460 return frappe.db.sql("""select tabAccount.name from `tabAccount`
461 where (tabAccount.report_type = "Profit and Loss"
462 or tabAccount.account_type in ("Income Account", "Temporary"))
463 and tabAccount.is_group=0
464 and tabAccount.`{key}` LIKE %(txt)s
Rushabh Mehta3574b372016-03-11 14:33:04 +0530465 {condition} {match_condition}
466 order by idx desc, name"""
Nabin Haitafd14f62015-10-19 11:55:28 +0530467 .format(condition=condition, match_condition=get_match_cond(doctype), key=searchfield), {
Suraj Shetty4b404c42018-09-27 15:39:34 +0530468 'txt': '%' + txt + '%',
Nabin Haitafd14f62015-10-19 11:55:28 +0530469 'company': filters.get("company", "")
Anand Doshi21e09a22015-10-29 12:21:41 +0530470 })
Nabin Hait3a15c922016-03-04 12:30:46 +0530471
472
473@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530474@frappe.validate_and_sanitize_search_inputs
Nabin Hait3a15c922016-03-04 12:30:46 +0530475def get_expense_account(doctype, txt, searchfield, start, page_len, filters):
476 from erpnext.controllers.queries import get_match_cond
Rushabh Mehta203cc962016-04-07 15:25:43 +0530477
Nabin Hait3a15c922016-03-04 12:30:46 +0530478 if not filters: filters = {}
479
480 condition = ""
481 if filters.get("company"):
482 condition += "and tabAccount.company = %(company)s"
Rushabh Mehta203cc962016-04-07 15:25:43 +0530483
Nabin Hait3a15c922016-03-04 12:30:46 +0530484 return frappe.db.sql("""select tabAccount.name from `tabAccount`
485 where (tabAccount.report_type = "Profit and Loss"
Mangesh-Khairnar5619db22019-08-21 14:49:24 +0530486 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 +0530487 and tabAccount.is_group=0
488 and tabAccount.docstatus!=2
489 and tabAccount.{key} LIKE %(txt)s
490 {condition} {match_condition}"""
Suraj Shettybfc195d2018-09-21 10:20:52 +0530491 .format(condition=condition, key=searchfield,
Nabin Hait3a15c922016-03-04 12:30:46 +0530492 match_condition=get_match_cond(doctype)), {
Neil Trini Lasrado30b97b02016-03-31 23:10:13 +0530493 'company': filters.get("company", ""),
Suraj Shetty4b404c42018-09-27 15:39:34 +0530494 'txt': '%' + txt + '%'
Maxwell Morais35572612016-07-21 23:42:59 -0300495 })
suyashphadtare049a88c2017-01-12 17:49:37 +0530496
497
498@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530499@frappe.validate_and_sanitize_search_inputs
suyashphadtare049a88c2017-01-12 17:49:37 +0530500def warehouse_query(doctype, txt, searchfield, start, page_len, filters):
501 # Should be used when item code is passed in filters.
suyashphadtare750a0672017-01-18 15:35:01 +0530502 conditions, bin_conditions = [], []
503 filter_dict = get_doctype_wise_filters(filters)
504
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530505 query = """select `tabWarehouse`.name,
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530506 CONCAT_WS(" : ", "Actual Qty", ifnull(round(`tabBin`.actual_qty, 2), 0 )) actual_qty
507 from `tabWarehouse` left join `tabBin`
508 on `tabBin`.warehouse = `tabWarehouse`.name {bin_conditions}
suyashphadtare34ab1362017-01-31 15:14:44 +0530509 where
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530510 `tabWarehouse`.`{key}` like {txt}
suyashphadtare34ab1362017-01-31 15:14:44 +0530511 {fcond} {mcond}
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530512 order by ifnull(`tabBin`.actual_qty, 0) desc
suyashphadtare34ab1362017-01-31 15:14:44 +0530513 limit
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530514 {start}, {page_len}
suyashphadtare34ab1362017-01-31 15:14:44 +0530515 """.format(
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530516 bin_conditions=get_filters_cond(doctype, filter_dict.get("Bin"),bin_conditions, ignore_permissions=True),
Suraj Shettybfc195d2018-09-21 10:20:52 +0530517 key=searchfield,
suyashphadtare34ab1362017-01-31 15:14:44 +0530518 fcond=get_filters_cond(doctype, filter_dict.get("Warehouse"), conditions),
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530519 mcond=get_match_cond(doctype),
520 start=start,
521 page_len=page_len,
522 txt=frappe.db.escape('%{0}%'.format(txt))
523 )
524
525 return frappe.db.sql(query)
suyashphadtare750a0672017-01-18 15:35:01 +0530526
527
528def get_doctype_wise_filters(filters):
529 # Helper function to seperate filters doctype_wise
530 filter_dict = defaultdict(list)
531 for row in filters:
532 filter_dict[row[0]].append(row)
533 return filter_dict
tundebabzy2a4fefc2017-11-29 06:23:09 +0100534
535
536@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530537@frappe.validate_and_sanitize_search_inputs
tundebabzy2a4fefc2017-11-29 06:23:09 +0100538def get_batch_numbers(doctype, txt, searchfield, start, page_len, filters):
rohitwaghchaure9fbed562018-01-12 16:22:33 +0530539 query = """select batch_id from `tabBatch`
Doridel Cahanap59e4c322018-08-06 17:15:18 +0800540 where disabled = 0
541 and (expiry_date >= CURDATE() or expiry_date IS NULL)
Suraj Shettybfc195d2018-09-21 10:20:52 +0530542 and name like {txt}""".format(txt = frappe.db.escape('%{0}%'.format(txt)))
tundebabzy2a4fefc2017-11-29 06:23:09 +0100543
rohitwaghchaure9fbed562018-01-12 16:22:33 +0530544 if filters and filters.get('item'):
Suraj Shettybfc195d2018-09-21 10:20:52 +0530545 query += " and item = {item}".format(item = frappe.db.escape(filters.get('item')))
tundebabzy2a4fefc2017-11-29 06:23:09 +0100546
Sachin Mane64f48db2018-01-08 17:57:32 +0530547 return frappe.db.sql(query, filters)
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530548
Himanshud94a38e2020-05-18 14:26:26 +0530549
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530550@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530551@frappe.validate_and_sanitize_search_inputs
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530552def item_manufacturer_query(doctype, txt, searchfield, start, page_len, filters):
Maricabac4b932019-09-16 19:44:28 +0530553 item_filters = [
554 ['manufacturer', 'like', '%' + txt + '%'],
555 ['item_code', '=', filters.get("item_code")]
556 ]
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530557
Maricabac4b932019-09-16 19:44:28 +0530558 item_manufacturers = frappe.get_all(
559 "Item Manufacturer",
560 fields=["manufacturer", "manufacturer_part_no"],
561 filters=item_filters,
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530562 limit_start=start,
563 limit_page_length=page_len,
564 as_list=1
565 )
Maricabac4b932019-09-16 19:44:28 +0530566 return item_manufacturers
Saqibd9956092019-11-18 11:46:55 +0530567
Himanshud94a38e2020-05-18 14:26:26 +0530568
Saqibd9956092019-11-18 11:46:55 +0530569@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530570@frappe.validate_and_sanitize_search_inputs
Saqibd9956092019-11-18 11:46:55 +0530571def get_purchase_receipts(doctype, txt, searchfield, start, page_len, filters):
572 query = """
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530573 select pr.name
Saqibd9956092019-11-18 11:46:55 +0530574 from `tabPurchase Receipt` pr, `tabPurchase Receipt Item` pritem
575 where pr.docstatus = 1 and pritem.parent = pr.name
576 and pr.name like {txt}""".format(txt = frappe.db.escape('%{0}%'.format(txt)))
577
578 if filters and filters.get('item_code'):
579 query += " and pritem.item_code = {item_code}".format(item_code = frappe.db.escape(filters.get('item_code')))
580
581 return frappe.db.sql(query, filters)
582
Himanshud94a38e2020-05-18 14:26:26 +0530583
Saqibd9956092019-11-18 11:46:55 +0530584@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530585@frappe.validate_and_sanitize_search_inputs
Saqibd9956092019-11-18 11:46:55 +0530586def get_purchase_invoices(doctype, txt, searchfield, start, page_len, filters):
587 query = """
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530588 select pi.name
Saqibd9956092019-11-18 11:46:55 +0530589 from `tabPurchase Invoice` pi, `tabPurchase Invoice Item` piitem
590 where pi.docstatus = 1 and piitem.parent = pi.name
591 and pi.name like {txt}""".format(txt = frappe.db.escape('%{0}%'.format(txt)))
592
593 if filters and filters.get('item_code'):
594 query += " and piitem.item_code = {item_code}".format(item_code = frappe.db.escape(filters.get('item_code')))
595
596 return frappe.db.sql(query, filters)
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530597
Himanshud94a38e2020-05-18 14:26:26 +0530598
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530599@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530600@frappe.validate_and_sanitize_search_inputs
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530601def get_tax_template(doctype, txt, searchfield, start, page_len, filters):
602
603 item_doc = frappe.get_cached_doc('Item', filters.get('item_code'))
604 item_group = filters.get('item_group')
605 taxes = item_doc.taxes or []
606
607 while item_group:
608 item_group_doc = frappe.get_cached_doc('Item Group', item_group)
609 taxes += item_group_doc.taxes or []
610 item_group = item_group_doc.parent_item_group
611
612 if not taxes:
613 return frappe.db.sql(""" SELECT name FROM `tabItem Tax Template` """)
614 else:
Marica0fcb05a2020-08-10 14:48:13 +0530615 valid_from = filters.get('valid_from')
616 valid_from = valid_from[1] if isinstance(valid_from, list) else valid_from
617
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530618 args = {
619 'item_code': filters.get('item_code'),
Marica0fcb05a2020-08-10 14:48:13 +0530620 'posting_date': valid_from,
mohammadahmad199041c0c9f2020-06-18 11:18:44 +0500621 'tax_category': filters.get('tax_category'),
622 'company': filters.get('company')
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530623 }
624
625 taxes = _get_item_tax_template(args, taxes, for_validate=True)
626 return [(d,) for d in set(taxes)]
Himanshud94a38e2020-05-18 14:26:26 +0530627
628
629def get_fields(doctype, fields=[]):
630 meta = frappe.get_meta(doctype)
631 fields.extend(meta.get_search_fields())
632
633 if meta.title_field and not meta.title_field.strip() in fields:
634 fields.insert(1, meta.title_field.strip())
635
636 return unique(fields)