blob: babc5bdd79705e5785b438720b68d6449a8d6f14 [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
168 ORDER BY idx DESC, name
169 LIMIT %(offset)s, %(limit)s
170 """.format(account_type_condition=account_type_condition, searchfield=searchfield),
171 dict(
172 account_types=filters.get("account_type"),
173 company=filters.get("company"),
174 currency=company_currency,
175 txt="%{}%".format(txt),
176 offset=start,
177 limit=page_len
178 )
179 )
180
181 return accounts
182
183 tax_accounts = get_accounts(True)
184
Nabin Hait0c21e2a2014-03-21 11:14:49 +0530185 if not tax_accounts:
Suraj Shetty1923ef02020-08-05 19:42:25 +0530186 tax_accounts = get_accounts(False)
Anand Doshibd67e872014-04-11 16:51:27 +0530187
Nabin Hait0c21e2a2014-03-21 11:14:49 +0530188 return tax_accounts
Saurabh02875592013-07-08 18:45:55 +0530189
Himanshud94a38e2020-05-18 14:26:26 +0530190
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530191@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530192@frappe.validate_and_sanitize_search_inputs
Rushabh Mehta203cc962016-04-07 15:25:43 +0530193def item_query(doctype, txt, searchfield, start, page_len, filters, as_dict=False):
Saurabh02875592013-07-08 18:45:55 +0530194 conditions = []
Saurabhf52dc072013-07-10 13:07:49 +0530195
marination3dbef9d2019-10-28 15:48:10 +0530196 #Get searchfields from meta and use in Item Link field query
marination1e754b12019-10-30 18:33:44 +0530197 meta = frappe.get_meta("Item", cached=True)
marination3dbef9d2019-10-28 15:48:10 +0530198 searchfields = meta.get_search_fields()
199
marination1e754b12019-10-30 18:33:44 +0530200 if "description" in searchfields:
201 searchfields.remove("description")
marination3dbef9d2019-10-28 15:48:10 +0530202
Rohit Waghchaurec42312e2019-11-19 19:05:23 +0530203 columns = ''
204 extra_searchfields = [field for field in searchfields
205 if not field in ["name", "item_group", "description"]]
206
207 if extra_searchfields:
208 columns = ", " + ", ".join(extra_searchfields)
marination1e754b12019-10-30 18:33:44 +0530209
210 searchfields = searchfields + [field for field in[searchfield or "name", "item_code", "item_group", "item_name"]
211 if not field in searchfields]
marination3dbef9d2019-10-28 15:48:10 +0530212 searchfields = " or ".join([field + " like %(txt)s" for field in searchfields])
213
Rushabh Mehtad5f9ebd2018-04-02 23:37:33 +0530214 description_cond = ''
215 if frappe.db.count('Item', cache=True) < 50000:
216 # scan description only if items are less than 50000
217 description_cond = 'or tabItem.description LIKE %(txt)s'
218
Prateeksha Singh984a7a72018-05-17 17:29:36 +0530219 return frappe.db.sql("""select tabItem.name,
Anand Doshibd67e872014-04-11 16:51:27 +0530220 if(length(tabItem.item_name) > 40,
221 concat(substr(tabItem.item_name, 1, 40), "..."), item_name) as item_name,
Prateeksha Singh984a7a72018-05-17 17:29:36 +0530222 tabItem.item_group,
Saurabh02875592013-07-08 18:45:55 +0530223 if(length(tabItem.description) > 40, \
Rohit Waghchaurec42312e2019-11-19 19:05:23 +0530224 concat(substr(tabItem.description, 1, 40), "..."), description) as description
marination1e754b12019-10-30 18:33:44 +0530225 {columns}
Anand Doshibd67e872014-04-11 16:51:27 +0530226 from tabItem
Anand Doshi22c0d782013-11-04 16:23:04 +0530227 where tabItem.docstatus < 2
Anand Doshi21e09a22015-10-29 12:21:41 +0530228 and tabItem.disabled=0
rohitwaghchaure79789072020-05-21 18:10:13 +0530229 and tabItem.has_variants=0
Rushabh Mehta864d1ea2014-06-23 12:20:12 +0530230 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 +0530231 and ({scond} or tabItem.item_code IN (select parent from `tabItem Barcode` where barcode LIKE %(txt)s)
Rohit Waghchaure2bfb0632019-03-02 21:47:55 +0530232 {description_cond})
Anand Doshi22c0d782013-11-04 16:23:04 +0530233 {fcond} {mcond}
Anand Doshi652bc072014-04-16 15:21:46 +0530234 order by
235 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
236 if(locate(%(_txt)s, item_name), locate(%(_txt)s, item_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530237 idx desc,
Anand Doshi652bc072014-04-16 15:21:46 +0530238 name, item_name
Rushabh Mehtabc4e2cd2017-10-17 12:30:34 +0530239 limit %(start)s, %(page_len)s """.format(
marination1e754b12019-10-30 18:33:44 +0530240 columns=columns,
marination3dbef9d2019-10-28 15:48:10 +0530241 scond=searchfields,
Nabin Haitc6285062016-03-30 13:10:25 +0530242 fcond=get_filters_cond(doctype, filters, conditions).replace('%', '%%'),
Rushabh Mehtad5f9ebd2018-04-02 23:37:33 +0530243 mcond=get_match_cond(doctype).replace('%', '%%'),
244 description_cond = description_cond),
Anand Doshi22c0d782013-11-04 16:23:04 +0530245 {
246 "today": nowdate(),
247 "txt": "%%%s%%" % txt,
Anand Doshi652bc072014-04-16 15:21:46 +0530248 "_txt": txt.replace("%", ""),
Anand Doshi22c0d782013-11-04 16:23:04 +0530249 "start": start,
250 "page_len": page_len
Rushabh Mehta203cc962016-04-07 15:25:43 +0530251 }, as_dict=as_dict)
Saurabh02875592013-07-08 18:45:55 +0530252
Himanshud94a38e2020-05-18 14:26:26 +0530253
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530254@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530255@frappe.validate_and_sanitize_search_inputs
Saurabh022ab632017-11-10 15:06:02 +0530256def bom(doctype, txt, searchfield, start, page_len, filters):
Anand Doshibd67e872014-04-11 16:51:27 +0530257 conditions = []
Himanshud94a38e2020-05-18 14:26:26 +0530258 fields = get_fields("BOM", ["name", "item"])
Saurabhf52dc072013-07-10 13:07:49 +0530259
Himanshud94a38e2020-05-18 14:26:26 +0530260 return frappe.db.sql("""select {fields}
Anand Doshibd67e872014-04-11 16:51:27 +0530261 from tabBOM
262 where tabBOM.docstatus=1
263 and tabBOM.is_active=1
Nabin Hait62211172016-03-16 16:22:03 +0530264 and tabBOM.`{key}` like %(txt)s
265 {fcond} {mcond}
266 order by
Rushabh Mehta3574b372016-03-11 14:33:04 +0530267 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
268 idx desc, name
Nabin Hait62211172016-03-16 16:22:03 +0530269 limit %(start)s, %(page_len)s """.format(
Himanshud94a38e2020-05-18 14:26:26 +0530270 fields=", ".join(fields),
Mangesh-Khairnar6a796912019-07-08 10:40:40 +0530271 fcond=get_filters_cond(doctype, filters, conditions).replace('%', '%%'),
Karthikeyan S747c2622019-07-19 22:49:21 +0530272 mcond=get_match_cond(doctype).replace('%', '%%'),
273 key=searchfield),
Mangesh-Khairnar6a796912019-07-08 10:40:40 +0530274 {
Karthikeyan S747c2622019-07-19 22:49:21 +0530275 'txt': '%' + txt + '%',
Rushabh Mehta3574b372016-03-11 14:33:04 +0530276 '_txt': txt.replace("%", ""),
Saurabh022ab632017-11-10 15:06:02 +0530277 'start': start or 0,
278 'page_len': page_len or 20
Rushabh Mehta3574b372016-03-11 14:33:04 +0530279 })
Saurabh02875592013-07-08 18:45:55 +0530280
Himanshud94a38e2020-05-18 14:26:26 +0530281
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530282@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530283@frappe.validate_and_sanitize_search_inputs
Saurabh02875592013-07-08 18:45:55 +0530284def get_project_name(doctype, txt, searchfield, start, page_len, filters):
285 cond = ''
Nabin Haitf71011a2014-08-21 11:34:31 +0530286 if filters.get('customer'):
Suraj Shetty6ea3de92018-09-26 18:15:53 +0530287 cond = """(`tabProject`.customer = %s or
rohitwaghchauree3304722018-08-27 11:43:57 +0530288 ifnull(`tabProject`.customer,"")="") and""" %(frappe.db.escape(filters.get("customer")))
Anand Doshibd67e872014-04-11 16:51:27 +0530289
Himanshud94a38e2020-05-18 14:26:26 +0530290 fields = get_fields("Project", ["name"])
291
292 return frappe.db.sql("""select {fields} from `tabProject`
Anand Doshibd67e872014-04-11 16:51:27 +0530293 where `tabProject`.status not in ("Completed", "Cancelled")
Rushabh Mehta3574b372016-03-11 14:33:04 +0530294 and {cond} `tabProject`.name like %(txt)s {match_cond}
295 order by
296 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
297 idx desc,
298 `tabProject`.name asc
299 limit {start}, {page_len}""".format(
Himanshud94a38e2020-05-18 14:26:26 +0530300 fields=", ".join(['`tabProject`.{0}'.format(f) for f in fields]),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530301 cond=cond,
302 match_cond=get_match_cond(doctype),
303 start=start,
304 page_len=page_len), {
305 "txt": "%{0}%".format(txt),
Nabin Haitdf4deba2016-03-16 11:16:31 +0530306 "_txt": txt.replace('%', '')
Rushabh Mehta3574b372016-03-11 14:33:04 +0530307 })
Anand Doshibd67e872014-04-11 16:51:27 +0530308
tundebabzyf6d738b2017-09-18 12:40:09 +0100309
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530310@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530311@frappe.validate_and_sanitize_search_inputs
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530312def get_delivery_notes_to_be_billed(doctype, txt, searchfield, start, page_len, filters, as_dict):
Himanshud94a38e2020-05-18 14:26:26 +0530313 fields = get_fields("Delivery Note", ["name", "customer", "posting_date"])
314
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530315 return frappe.db.sql("""
Himanshud94a38e2020-05-18 14:26:26 +0530316 select %(fields)s
Anand Doshibd67e872014-04-11 16:51:27 +0530317 from `tabDelivery Note`
318 where `tabDelivery Note`.`%(key)s` like %(txt)s and
tundebabzyf6d738b2017-09-18 12:40:09 +0100319 `tabDelivery Note`.docstatus = 1
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530320 and status not in ("Stopped", "Closed") %(fcond)s
tundebabzyf6d738b2017-09-18 12:40:09 +0100321 and (
322 (`tabDelivery Note`.is_return = 0 and `tabDelivery Note`.per_billed < 100)
323 or `tabDelivery Note`.grand_total = 0
324 or (
325 `tabDelivery Note`.is_return = 1
326 and return_against in (select name from `tabDelivery Note` where per_billed < 100)
327 )
328 )
rohitwaghchaured07a3e12019-05-15 07:46:28 +0530329 %(mcond)s order by `tabDelivery Note`.`%(key)s` asc limit %(start)s, %(page_len)s
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530330 """ % {
Himanshud94a38e2020-05-18 14:26:26 +0530331 "fields": ", ".join(["`tabDelivery Note`.{0}".format(f) for f in fields]),
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530332 "key": searchfield,
333 "fcond": get_filters_cond(doctype, filters, []),
334 "mcond": get_match_cond(doctype),
rohitwaghchaured07a3e12019-05-15 07:46:28 +0530335 "start": start,
336 "page_len": page_len,
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530337 "txt": "%(txt)s"
tundebabzyf6d738b2017-09-18 12:40:09 +0100338 }, {"txt": ("%%%s%%" % txt)}, as_dict=as_dict)
339
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530340
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530341@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530342@frappe.validate_and_sanitize_search_inputs
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530343def get_batch_no(doctype, txt, searchfield, start, page_len, filters):
Neil Trini Lasradoebb60f52015-07-08 14:36:09 +0530344 cond = ""
345 if filters.get("posting_date"):
Nabin Hait7918b922018-01-31 15:30:03 +0530346 cond = "and (batch.expiry_date is null or batch.expiry_date >= %(posting_date)s)"
Rushabh Mehtab6398be2015-08-26 10:50:16 +0530347
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530348 batch_nos = None
349 args = {
350 'item_code': filters.get("item_code"),
351 'warehouse': filters.get("warehouse"),
352 'posting_date': filters.get('posting_date'),
Anand Doshi0dc79f42015-04-06 12:59:34 +0530353 'txt': "%{0}%".format(txt),
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530354 "start": start,
355 "page_len": page_len
356 }
357
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530358 having_clause = "having sum(sle.actual_qty) > 0"
359 if filters.get("is_return"):
360 having_clause = ""
361
Anand Doshi0dc79f42015-04-06 12:59:34 +0530362 if args.get('warehouse'):
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530363 batch_nos = frappe.db.sql("""select sle.batch_no, round(sum(sle.actual_qty),2), sle.stock_uom,
364 concat('MFG-',batch.manufacturing_date), concat('EXP-',batch.expiry_date)
365 from `tabStock Ledger Entry` sle
366 INNER JOIN `tabBatch` batch on sle.batch_no = batch.name
367 where
368 batch.disabled = 0
369 and sle.item_code = %(item_code)s
370 and sle.warehouse = %(warehouse)s
371 and (sle.batch_no like %(txt)s
Sun Howwrongbum088be372019-12-24 12:29:25 +0530372 or batch.expiry_date like %(txt)s
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530373 or batch.manufacturing_date like %(txt)s)
374 and batch.docstatus < 2
375 {cond}
376 {match_conditions}
377 group by batch_no {having_clause}
378 order by batch.expiry_date, sle.batch_no desc
379 limit %(start)s, %(page_len)s""".format(
380 cond=cond,
381 match_conditions=get_match_cond(doctype),
382 having_clause = having_clause
383 ), args)
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530384
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530385 return batch_nos
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530386 else:
sivankar621740e2018-02-12 14:33:40 +0530387 return frappe.db.sql("""select name, concat('MFG-', manufacturing_date), concat('EXP-',expiry_date) from `tabBatch` batch
Doridel Cahanap59e4c322018-08-06 17:15:18 +0800388 where batch.disabled = 0
389 and item = %(item_code)s
sivankar621740e2018-02-12 14:33:40 +0530390 and (name like %(txt)s
Sun Howwrongbum088be372019-12-24 12:29:25 +0530391 or expiry_date like %(txt)s
sivankar621740e2018-02-12 14:33:40 +0530392 or manufacturing_date like %(txt)s)
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530393 and docstatus < 2
Neil Trini Lasradoebb60f52015-07-08 14:36:09 +0530394 {0}
Anand Doshi0dc79f42015-04-06 12:59:34 +0530395 {match_conditions}
396 order by expiry_date, name desc
Nabin Haite52ee552015-09-02 10:55:32 +0530397 limit %(start)s, %(page_len)s""".format(cond, match_conditions=get_match_cond(doctype)), args)
Nabin Haitea4aa042014-05-28 12:56:28 +0530398
Himanshud94a38e2020-05-18 14:26:26 +0530399
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530400@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530401@frappe.validate_and_sanitize_search_inputs
Nabin Haitea4aa042014-05-28 12:56:28 +0530402def get_account_list(doctype, txt, searchfield, start, page_len, filters):
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530403 filter_list = []
Nabin Haitea4aa042014-05-28 12:56:28 +0530404
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530405 if isinstance(filters, dict):
406 for key, val in filters.items():
407 if isinstance(val, (list, tuple)):
408 filter_list.append([doctype, key, val[0], val[1]])
409 else:
410 filter_list.append([doctype, key, "=", val])
bhupeshg2e2e973f2015-04-14 22:15:24 +0530411 elif isinstance(filters, list):
412 filter_list.extend(filters)
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530413
Rushabh Mehta38c6b522015-04-23 13:14:17 +0530414 if "is_group" not in [d[1] for d in filter_list]:
415 filter_list.append(["Account", "is_group", "=", "0"])
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530416
417 if searchfield and txt:
418 filter_list.append([doctype, searchfield, "like", "%%%s%%" % txt])
419
Rushabh Mehtac0bb4532014-09-09 16:15:35 +0530420 return frappe.desk.reportview.execute("Account", filters = filter_list,
Nabin Haitea4aa042014-05-28 12:56:28 +0530421 fields = ["name", "parent_account"],
422 limit_start=start, limit_page_length=page_len, as_list=True)
Anand Doshifaefeaa2014-06-24 18:53:04 +0530423
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530424@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530425@frappe.validate_and_sanitize_search_inputs
Marica299e2172020-04-28 13:00:04 +0530426def get_blanket_orders(doctype, txt, searchfield, start, page_len, filters):
427 return frappe.db.sql("""select distinct bo.name, bo.blanket_order_type, bo.to_date
428 from `tabBlanket Order` bo, `tabBlanket Order Item` boi
429 where
430 boi.parent = bo.name
431 and boi.item_code = {item_code}
432 and bo.blanket_order_type = '{blanket_order_type}'
433 and bo.company = {company}
434 and bo.docstatus = 1"""
435 .format(item_code = frappe.db.escape(filters.get("item")),
436 blanket_order_type = filters.get("blanket_order_type"),
437 company = frappe.db.escape(filters.get("company"))
438 ))
Nabin Haitafd14f62015-10-19 11:55:28 +0530439
Himanshud94a38e2020-05-18 14:26:26 +0530440
Nabin Haitafd14f62015-10-19 11:55:28 +0530441@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530442@frappe.validate_and_sanitize_search_inputs
Nabin Haitafd14f62015-10-19 11:55:28 +0530443def get_income_account(doctype, txt, searchfield, start, page_len, filters):
444 from erpnext.controllers.queries import get_match_cond
445
446 # income account can be any Credit account,
447 # but can also be a Asset account with account_type='Income Account' in special circumstances.
448 # Hence the first condition is an "OR"
449 if not filters: filters = {}
450
Anand Doshi21e09a22015-10-29 12:21:41 +0530451 condition = ""
Nabin Haitafd14f62015-10-19 11:55:28 +0530452 if filters.get("company"):
453 condition += "and tabAccount.company = %(company)s"
Anand Doshi21e09a22015-10-29 12:21:41 +0530454
Nabin Haitafd14f62015-10-19 11:55:28 +0530455 return frappe.db.sql("""select tabAccount.name from `tabAccount`
456 where (tabAccount.report_type = "Profit and Loss"
457 or tabAccount.account_type in ("Income Account", "Temporary"))
458 and tabAccount.is_group=0
459 and tabAccount.`{key}` LIKE %(txt)s
Rushabh Mehta3574b372016-03-11 14:33:04 +0530460 {condition} {match_condition}
461 order by idx desc, name"""
Nabin Haitafd14f62015-10-19 11:55:28 +0530462 .format(condition=condition, match_condition=get_match_cond(doctype), key=searchfield), {
Suraj Shetty4b404c42018-09-27 15:39:34 +0530463 'txt': '%' + txt + '%',
Nabin Haitafd14f62015-10-19 11:55:28 +0530464 'company': filters.get("company", "")
Anand Doshi21e09a22015-10-29 12:21:41 +0530465 })
Nabin Hait3a15c922016-03-04 12:30:46 +0530466
467
468@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530469@frappe.validate_and_sanitize_search_inputs
Nabin Hait3a15c922016-03-04 12:30:46 +0530470def get_expense_account(doctype, txt, searchfield, start, page_len, filters):
471 from erpnext.controllers.queries import get_match_cond
Rushabh Mehta203cc962016-04-07 15:25:43 +0530472
Nabin Hait3a15c922016-03-04 12:30:46 +0530473 if not filters: filters = {}
474
475 condition = ""
476 if filters.get("company"):
477 condition += "and tabAccount.company = %(company)s"
Rushabh Mehta203cc962016-04-07 15:25:43 +0530478
Nabin Hait3a15c922016-03-04 12:30:46 +0530479 return frappe.db.sql("""select tabAccount.name from `tabAccount`
480 where (tabAccount.report_type = "Profit and Loss"
Mangesh-Khairnar5619db22019-08-21 14:49:24 +0530481 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 +0530482 and tabAccount.is_group=0
483 and tabAccount.docstatus!=2
484 and tabAccount.{key} LIKE %(txt)s
485 {condition} {match_condition}"""
Suraj Shettybfc195d2018-09-21 10:20:52 +0530486 .format(condition=condition, key=searchfield,
Nabin Hait3a15c922016-03-04 12:30:46 +0530487 match_condition=get_match_cond(doctype)), {
Neil Trini Lasrado30b97b02016-03-31 23:10:13 +0530488 'company': filters.get("company", ""),
Suraj Shetty4b404c42018-09-27 15:39:34 +0530489 'txt': '%' + txt + '%'
Maxwell Morais35572612016-07-21 23:42:59 -0300490 })
suyashphadtare049a88c2017-01-12 17:49:37 +0530491
492
493@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530494@frappe.validate_and_sanitize_search_inputs
suyashphadtare049a88c2017-01-12 17:49:37 +0530495def warehouse_query(doctype, txt, searchfield, start, page_len, filters):
496 # Should be used when item code is passed in filters.
suyashphadtare750a0672017-01-18 15:35:01 +0530497 conditions, bin_conditions = [], []
498 filter_dict = get_doctype_wise_filters(filters)
499
500 sub_query = """ select round(`tabBin`.actual_qty, 2) from `tabBin`
suyashphadtare34ab1362017-01-31 15:14:44 +0530501 where `tabBin`.warehouse = `tabWarehouse`.name
502 {bin_conditions} """.format(
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530503 bin_conditions=get_filters_cond(doctype, filter_dict.get("Bin"),
Nabin Hait4e6ff8c2017-05-09 15:09:10 +0530504 bin_conditions, ignore_permissions=True))
suyashphadtare750a0672017-01-18 15:35:01 +0530505
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530506 query = """select `tabWarehouse`.name,
suyashphadtare34ab1362017-01-31 15:14:44 +0530507 CONCAT_WS(" : ", "Actual Qty", ifnull( ({sub_query}), 0) ) as actual_qty
508 from `tabWarehouse`
509 where
Suraj Shetty6ea3de92018-09-26 18:15:53 +0530510 `tabWarehouse`.`{key}` like {txt}
suyashphadtare34ab1362017-01-31 15:14:44 +0530511 {fcond} {mcond}
512 order by
513 `tabWarehouse`.name desc
514 limit
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530515 {start}, {page_len}
suyashphadtare34ab1362017-01-31 15:14:44 +0530516 """.format(
517 sub_query=sub_query,
Suraj Shettybfc195d2018-09-21 10:20:52 +0530518 key=searchfield,
suyashphadtare34ab1362017-01-31 15:14:44 +0530519 fcond=get_filters_cond(doctype, filter_dict.get("Warehouse"), conditions),
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530520 mcond=get_match_cond(doctype),
521 start=start,
522 page_len=page_len,
523 txt=frappe.db.escape('%{0}%'.format(txt))
524 )
525
526 return frappe.db.sql(query)
suyashphadtare750a0672017-01-18 15:35:01 +0530527
528
529def get_doctype_wise_filters(filters):
530 # Helper function to seperate filters doctype_wise
531 filter_dict = defaultdict(list)
532 for row in filters:
533 filter_dict[row[0]].append(row)
534 return filter_dict
tundebabzy2a4fefc2017-11-29 06:23:09 +0100535
536
537@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530538@frappe.validate_and_sanitize_search_inputs
tundebabzy2a4fefc2017-11-29 06:23:09 +0100539def get_batch_numbers(doctype, txt, searchfield, start, page_len, filters):
rohitwaghchaure9fbed562018-01-12 16:22:33 +0530540 query = """select batch_id from `tabBatch`
Doridel Cahanap59e4c322018-08-06 17:15:18 +0800541 where disabled = 0
542 and (expiry_date >= CURDATE() or expiry_date IS NULL)
Suraj Shettybfc195d2018-09-21 10:20:52 +0530543 and name like {txt}""".format(txt = frappe.db.escape('%{0}%'.format(txt)))
tundebabzy2a4fefc2017-11-29 06:23:09 +0100544
rohitwaghchaure9fbed562018-01-12 16:22:33 +0530545 if filters and filters.get('item'):
Suraj Shettybfc195d2018-09-21 10:20:52 +0530546 query += " and item = {item}".format(item = frappe.db.escape(filters.get('item')))
tundebabzy2a4fefc2017-11-29 06:23:09 +0100547
Sachin Mane64f48db2018-01-08 17:57:32 +0530548 return frappe.db.sql(query, filters)
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530549
Himanshud94a38e2020-05-18 14:26:26 +0530550
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530551@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530552@frappe.validate_and_sanitize_search_inputs
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530553def item_manufacturer_query(doctype, txt, searchfield, start, page_len, filters):
Maricabac4b932019-09-16 19:44:28 +0530554 item_filters = [
555 ['manufacturer', 'like', '%' + txt + '%'],
556 ['item_code', '=', filters.get("item_code")]
557 ]
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530558
Maricabac4b932019-09-16 19:44:28 +0530559 item_manufacturers = frappe.get_all(
560 "Item Manufacturer",
561 fields=["manufacturer", "manufacturer_part_no"],
562 filters=item_filters,
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530563 limit_start=start,
564 limit_page_length=page_len,
565 as_list=1
566 )
Maricabac4b932019-09-16 19:44:28 +0530567 return item_manufacturers
Saqibd9956092019-11-18 11:46:55 +0530568
Himanshud94a38e2020-05-18 14:26:26 +0530569
Saqibd9956092019-11-18 11:46:55 +0530570@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530571@frappe.validate_and_sanitize_search_inputs
Saqibd9956092019-11-18 11:46:55 +0530572def get_purchase_receipts(doctype, txt, searchfield, start, page_len, filters):
573 query = """
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530574 select pr.name
Saqibd9956092019-11-18 11:46:55 +0530575 from `tabPurchase Receipt` pr, `tabPurchase Receipt Item` pritem
576 where pr.docstatus = 1 and pritem.parent = pr.name
577 and pr.name like {txt}""".format(txt = frappe.db.escape('%{0}%'.format(txt)))
578
579 if filters and filters.get('item_code'):
580 query += " and pritem.item_code = {item_code}".format(item_code = frappe.db.escape(filters.get('item_code')))
581
582 return frappe.db.sql(query, filters)
583
Himanshud94a38e2020-05-18 14:26:26 +0530584
Saqibd9956092019-11-18 11:46:55 +0530585@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530586@frappe.validate_and_sanitize_search_inputs
Saqibd9956092019-11-18 11:46:55 +0530587def get_purchase_invoices(doctype, txt, searchfield, start, page_len, filters):
588 query = """
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530589 select pi.name
Saqibd9956092019-11-18 11:46:55 +0530590 from `tabPurchase Invoice` pi, `tabPurchase Invoice Item` piitem
591 where pi.docstatus = 1 and piitem.parent = pi.name
592 and pi.name like {txt}""".format(txt = frappe.db.escape('%{0}%'.format(txt)))
593
594 if filters and filters.get('item_code'):
595 query += " and piitem.item_code = {item_code}".format(item_code = frappe.db.escape(filters.get('item_code')))
596
597 return frappe.db.sql(query, filters)
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530598
Himanshud94a38e2020-05-18 14:26:26 +0530599
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530600@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530601@frappe.validate_and_sanitize_search_inputs
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530602def get_tax_template(doctype, txt, searchfield, start, page_len, filters):
603
604 item_doc = frappe.get_cached_doc('Item', filters.get('item_code'))
605 item_group = filters.get('item_group')
606 taxes = item_doc.taxes or []
607
608 while item_group:
609 item_group_doc = frappe.get_cached_doc('Item Group', item_group)
610 taxes += item_group_doc.taxes or []
611 item_group = item_group_doc.parent_item_group
612
613 if not taxes:
614 return frappe.db.sql(""" SELECT name FROM `tabItem Tax Template` """)
615 else:
616 args = {
617 'item_code': filters.get('item_code'),
618 'posting_date': filters.get('valid_from'),
mohammadahmad199041c0c9f2020-06-18 11:18:44 +0500619 'tax_category': filters.get('tax_category'),
620 'company': filters.get('company')
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530621 }
622
623 taxes = _get_item_tax_template(args, taxes, for_validate=True)
624 return [(d,) for d in set(taxes)]
Himanshud94a38e2020-05-18 14:26:26 +0530625
626
627def get_fields(doctype, fields=[]):
628 meta = frappe.get_meta(doctype)
629 fields.extend(meta.get_search_fields())
630
631 if meta.title_field and not meta.title_field.strip() in fields:
632 fields.insert(1, meta.title_field.strip())
633
634 return unique(fields)