blob: d9465917ec6e72aab7cf1e7b201fbd4ddfa8319c [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
Saurabh02875592013-07-08 18:45:55 +053013 # searches for active employees
14def employee_query(doctype, txt, searchfield, start, page_len, filters):
Kanchan Chauhan7652b852016-11-16 15:29:01 +053015 conditions = []
Himanshud94a38e2020-05-18 14:26:26 +053016 fields = get_fields("Employee", ["name", "employee_name"])
17
18 return frappe.db.sql("""select {fields} from `tabEmployee`
Anand Doshibd67e872014-04-11 16:51:27 +053019 where status = 'Active'
20 and docstatus < 2
Anand Doshi48d3b542014-07-09 13:15:03 +053021 and ({key} like %(txt)s
22 or employee_name like %(txt)s)
Kanchan Chauhan7652b852016-11-16 15:29:01 +053023 {fcond} {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +053024 order by
Anand Doshi48d3b542014-07-09 13:15:03 +053025 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
26 if(locate(%(_txt)s, employee_name), locate(%(_txt)s, employee_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +053027 idx desc,
Anand Doshi652bc072014-04-16 15:21:46 +053028 name, employee_name
Anand Doshi48d3b542014-07-09 13:15:03 +053029 limit %(start)s, %(page_len)s""".format(**{
Himanshud94a38e2020-05-18 14:26:26 +053030 'fields': ", ".join(fields),
Anand Doshi48d3b542014-07-09 13:15:03 +053031 'key': searchfield,
Kanchan Chauhan7652b852016-11-16 15:29:01 +053032 'fcond': get_filters_cond(doctype, filters, conditions),
Anand Doshi48d3b542014-07-09 13:15:03 +053033 'mcond': get_match_cond(doctype)
34 }), {
35 'txt': "%%%s%%" % txt,
36 '_txt': txt.replace("%", ""),
37 'start': start,
38 'page_len': page_len
39 })
Saurabh02875592013-07-08 18:45:55 +053040
Himanshud94a38e2020-05-18 14:26:26 +053041
42# searches for leads which are not converted
Anand Doshibd67e872014-04-11 16:51:27 +053043def lead_query(doctype, txt, searchfield, start, page_len, filters):
Himanshud94a38e2020-05-18 14:26:26 +053044 fields = get_fields("Lead", ["name", "lead_name", "company_name"])
45
46 return frappe.db.sql("""select {fields} from `tabLead`
Anand Doshibd67e872014-04-11 16:51:27 +053047 where docstatus < 2
48 and ifnull(status, '') != 'Converted'
Anand Doshi48d3b542014-07-09 13:15:03 +053049 and ({key} like %(txt)s
50 or lead_name like %(txt)s
51 or company_name like %(txt)s)
52 {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +053053 order by
Anand Doshi48d3b542014-07-09 13:15:03 +053054 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
55 if(locate(%(_txt)s, lead_name), locate(%(_txt)s, lead_name), 99999),
56 if(locate(%(_txt)s, company_name), locate(%(_txt)s, company_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +053057 idx desc,
Anand Doshi652bc072014-04-16 15:21:46 +053058 name, lead_name
Anand Doshi48d3b542014-07-09 13:15:03 +053059 limit %(start)s, %(page_len)s""".format(**{
Himanshud94a38e2020-05-18 14:26:26 +053060 'fields': ", ".join(fields),
Anand Doshi48d3b542014-07-09 13:15:03 +053061 'key': searchfield,
62 'mcond':get_match_cond(doctype)
63 }), {
64 'txt': "%%%s%%" % txt,
65 '_txt': txt.replace("%", ""),
66 'start': start,
67 'page_len': page_len
68 })
Saurabh02875592013-07-08 18:45:55 +053069
Himanshud94a38e2020-05-18 14:26:26 +053070
Saurabh02875592013-07-08 18:45:55 +053071 # searches for customer
72def customer_query(doctype, txt, searchfield, start, page_len, filters):
KanchanChauhan4b888b92017-07-25 14:03:01 +053073 conditions = []
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053074 cust_master_name = frappe.defaults.get_user_default("cust_master_name")
Saurabhf52dc072013-07-10 13:07:49 +053075
Saurabh02875592013-07-08 18:45:55 +053076 if cust_master_name == "Customer Name":
77 fields = ["name", "customer_group", "territory"]
78 else:
79 fields = ["name", "customer_name", "customer_group", "territory"]
Rushabh Mehtab92087c2017-01-13 18:53:11 +053080
Himanshud94a38e2020-05-18 14:26:26 +053081 fields = get_fields("Customer", fields)
Saurabhf52dc072013-07-10 13:07:49 +053082
Himanshud94a38e2020-05-18 14:26:26 +053083 searchfields = frappe.get_meta("Customer").get_search_fields()
Console Admin86231662017-06-23 20:32:52 +030084 searchfields = " or ".join([field + " like %(txt)s" for field in searchfields])
Saurabh02875592013-07-08 18:45:55 +053085
Anand Doshi48d3b542014-07-09 13:15:03 +053086 return frappe.db.sql("""select {fields} from `tabCustomer`
Anand Doshibd67e872014-04-11 16:51:27 +053087 where docstatus < 2
Console Admin86231662017-06-23 20:32:52 +030088 and ({scond}) and disabled=0
KanchanChauhan4b888b92017-07-25 14:03:01 +053089 {fcond} {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +053090 order by
Anand Doshi48d3b542014-07-09 13:15:03 +053091 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
92 if(locate(%(_txt)s, customer_name), locate(%(_txt)s, customer_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +053093 idx desc,
Anand Doshibd67e872014-04-11 16:51:27 +053094 name, customer_name
Anand Doshi48d3b542014-07-09 13:15:03 +053095 limit %(start)s, %(page_len)s""".format(**{
Himanshud94a38e2020-05-18 14:26:26 +053096 "fields": ", ".join(fields),
Console Admin86231662017-06-23 20:32:52 +030097 "scond": searchfields,
KanchanChauhan4b888b92017-07-25 14:03:01 +053098 "mcond": get_match_cond(doctype),
99 "fcond": get_filters_cond(doctype, filters, conditions).replace('%', '%%'),
Anand Doshi48d3b542014-07-09 13:15:03 +0530100 }), {
101 'txt': "%%%s%%" % txt,
102 '_txt': txt.replace("%", ""),
103 'start': start,
104 'page_len': page_len
105 })
Saurabh02875592013-07-08 18:45:55 +0530106
Himanshud94a38e2020-05-18 14:26:26 +0530107
Saurabh02875592013-07-08 18:45:55 +0530108# searches for supplier
109def supplier_query(doctype, txt, searchfield, start, page_len, filters):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530110 supp_master_name = frappe.defaults.get_user_default("supp_master_name")
Anand Doshibd67e872014-04-11 16:51:27 +0530111 if supp_master_name == "Supplier Name":
Zlash652e080982018-04-19 18:37:53 +0530112 fields = ["name", "supplier_group"]
Anand Doshibd67e872014-04-11 16:51:27 +0530113 else:
Zlash652e080982018-04-19 18:37:53 +0530114 fields = ["name", "supplier_name", "supplier_group"]
Himanshud94a38e2020-05-18 14:26:26 +0530115
116 fields = get_fields("Supplier", fields)
Saurabh02875592013-07-08 18:45:55 +0530117
Anand Doshi48d3b542014-07-09 13:15:03 +0530118 return frappe.db.sql("""select {field} from `tabSupplier`
Anand Doshibd67e872014-04-11 16:51:27 +0530119 where docstatus < 2
Anand Doshi48d3b542014-07-09 13:15:03 +0530120 and ({key} like %(txt)s
shreyas29b565f2016-01-25 17:30:49 +0530121 or supplier_name like %(txt)s) and disabled=0
Anand Doshi48d3b542014-07-09 13:15:03 +0530122 {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +0530123 order by
Anand Doshi48d3b542014-07-09 13:15:03 +0530124 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
125 if(locate(%(_txt)s, supplier_name), locate(%(_txt)s, supplier_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530126 idx desc,
Anand Doshibd67e872014-04-11 16:51:27 +0530127 name, supplier_name
Anand Doshi48d3b542014-07-09 13:15:03 +0530128 limit %(start)s, %(page_len)s """.format(**{
Himanshud94a38e2020-05-18 14:26:26 +0530129 'field': ', '.join(fields),
Anand Doshi48d3b542014-07-09 13:15:03 +0530130 'key': searchfield,
131 'mcond':get_match_cond(doctype)
132 }), {
133 'txt': "%%%s%%" % txt,
134 '_txt': txt.replace("%", ""),
135 'start': start,
136 'page_len': page_len
137 })
Anand Doshibd67e872014-04-11 16:51:27 +0530138
Himanshud94a38e2020-05-18 14:26:26 +0530139
Nabin Hait9a380ef2013-07-16 17:24:17 +0530140def tax_account_query(doctype, txt, searchfield, start, page_len, filters):
Deepesh Gargfbf6e562020-03-31 10:45:32 +0530141 company_currency = erpnext.get_company_currency(filters.get('company'))
142
Anand Doshibd67e872014-04-11 16:51:27 +0530143 tax_accounts = frappe.db.sql("""select name, parent_account from tabAccount
144 where tabAccount.docstatus!=2
Nabin Hait0c21e2a2014-03-21 11:14:49 +0530145 and account_type in (%s)
Rushabh Mehta38c6b522015-04-23 13:14:17 +0530146 and is_group = 0
Nabin Hait9a380ef2013-07-16 17:24:17 +0530147 and company = %s
Deepesh Gargfbf6e562020-03-31 10:45:32 +0530148 and account_currency = %s
Nabin Hait9a380ef2013-07-16 17:24:17 +0530149 and `%s` LIKE %s
Rushabh Mehta3574b372016-03-11 14:33:04 +0530150 order by idx desc, name
Anand Doshibd67e872014-04-11 16:51:27 +0530151 limit %s, %s""" %
Deepesh Gargfbf6e562020-03-31 10:45:32 +0530152 (", ".join(['%s']*len(filters.get("account_type"))), "%s", "%s", searchfield, "%s", "%s", "%s"),
153 tuple(filters.get("account_type") + [filters.get("company"), company_currency, "%%%s%%" % txt,
Nabin Hait0c21e2a2014-03-21 11:14:49 +0530154 start, page_len]))
155 if not tax_accounts:
Anand Doshibd67e872014-04-11 16:51:27 +0530156 tax_accounts = frappe.db.sql("""select name, parent_account from tabAccount
Rushabh Mehta38c6b522015-04-23 13:14:17 +0530157 where tabAccount.docstatus!=2 and is_group = 0
Deepesh Gargfbf6e562020-03-31 10:45:32 +0530158 and company = %s and account_currency = %s and `%s` LIKE %s limit %s, %s""" #nosec
159 % ("%s", "%s", searchfield, "%s", "%s", "%s"),
160 (filters.get("company"), company_currency, "%%%s%%" % txt, start, page_len))
Anand Doshibd67e872014-04-11 16:51:27 +0530161
Nabin Hait0c21e2a2014-03-21 11:14:49 +0530162 return tax_accounts
Saurabh02875592013-07-08 18:45:55 +0530163
Himanshud94a38e2020-05-18 14:26:26 +0530164
Rushabh Mehta203cc962016-04-07 15:25:43 +0530165def item_query(doctype, txt, searchfield, start, page_len, filters, as_dict=False):
Saurabh02875592013-07-08 18:45:55 +0530166 conditions = []
Saurabhf52dc072013-07-10 13:07:49 +0530167
marination3dbef9d2019-10-28 15:48:10 +0530168 #Get searchfields from meta and use in Item Link field query
marination1e754b12019-10-30 18:33:44 +0530169 meta = frappe.get_meta("Item", cached=True)
marination3dbef9d2019-10-28 15:48:10 +0530170 searchfields = meta.get_search_fields()
171
marination1e754b12019-10-30 18:33:44 +0530172 if "description" in searchfields:
173 searchfields.remove("description")
marination3dbef9d2019-10-28 15:48:10 +0530174
Rohit Waghchaurec42312e2019-11-19 19:05:23 +0530175 columns = ''
176 extra_searchfields = [field for field in searchfields
177 if not field in ["name", "item_group", "description"]]
178
179 if extra_searchfields:
180 columns = ", " + ", ".join(extra_searchfields)
marination1e754b12019-10-30 18:33:44 +0530181
182 searchfields = searchfields + [field for field in[searchfield or "name", "item_code", "item_group", "item_name"]
183 if not field in searchfields]
marination3dbef9d2019-10-28 15:48:10 +0530184 searchfields = " or ".join([field + " like %(txt)s" for field in searchfields])
185
Rushabh Mehtad5f9ebd2018-04-02 23:37:33 +0530186 description_cond = ''
187 if frappe.db.count('Item', cache=True) < 50000:
188 # scan description only if items are less than 50000
189 description_cond = 'or tabItem.description LIKE %(txt)s'
190
rohitwaghchaure05ac7212020-04-06 10:17:57 +0530191 extra_cond = " and tabItem.has_variants=0"
192 if (filters and isinstance(filters, dict)
193 and filters.get("doctype") == "BOM"):
194 extra_cond = ""
195 del filters["doctype"]
196
Prateeksha Singh984a7a72018-05-17 17:29:36 +0530197 return frappe.db.sql("""select tabItem.name,
Anand Doshibd67e872014-04-11 16:51:27 +0530198 if(length(tabItem.item_name) > 40,
199 concat(substr(tabItem.item_name, 1, 40), "..."), item_name) as item_name,
Prateeksha Singh984a7a72018-05-17 17:29:36 +0530200 tabItem.item_group,
Saurabh02875592013-07-08 18:45:55 +0530201 if(length(tabItem.description) > 40, \
Rohit Waghchaurec42312e2019-11-19 19:05:23 +0530202 concat(substr(tabItem.description, 1, 40), "..."), description) as description
marination1e754b12019-10-30 18:33:44 +0530203 {columns}
Anand Doshibd67e872014-04-11 16:51:27 +0530204 from tabItem
Anand Doshi22c0d782013-11-04 16:23:04 +0530205 where tabItem.docstatus < 2
Anand Doshi21e09a22015-10-29 12:21:41 +0530206 and tabItem.disabled=0
Rushabh Mehta864d1ea2014-06-23 12:20:12 +0530207 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 +0530208 and ({scond} or tabItem.item_code IN (select parent from `tabItem Barcode` where barcode LIKE %(txt)s)
Rohit Waghchaure2bfb0632019-03-02 21:47:55 +0530209 {description_cond})
rohitwaghchaure05ac7212020-04-06 10:17:57 +0530210 {extra_cond}
Anand Doshi22c0d782013-11-04 16:23:04 +0530211 {fcond} {mcond}
Anand Doshi652bc072014-04-16 15:21:46 +0530212 order by
213 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
214 if(locate(%(_txt)s, item_name), locate(%(_txt)s, item_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530215 idx desc,
Anand Doshi652bc072014-04-16 15:21:46 +0530216 name, item_name
Rushabh Mehtabc4e2cd2017-10-17 12:30:34 +0530217 limit %(start)s, %(page_len)s """.format(
218 key=searchfield,
marination1e754b12019-10-30 18:33:44 +0530219 columns=columns,
marination3dbef9d2019-10-28 15:48:10 +0530220 scond=searchfields,
rohitwaghchaure05ac7212020-04-06 10:17:57 +0530221 extra_cond=extra_cond,
Nabin Haitc6285062016-03-30 13:10:25 +0530222 fcond=get_filters_cond(doctype, filters, conditions).replace('%', '%%'),
Rushabh Mehtad5f9ebd2018-04-02 23:37:33 +0530223 mcond=get_match_cond(doctype).replace('%', '%%'),
224 description_cond = description_cond),
Anand Doshi22c0d782013-11-04 16:23:04 +0530225 {
226 "today": nowdate(),
227 "txt": "%%%s%%" % txt,
Anand Doshi652bc072014-04-16 15:21:46 +0530228 "_txt": txt.replace("%", ""),
Anand Doshi22c0d782013-11-04 16:23:04 +0530229 "start": start,
230 "page_len": page_len
Rushabh Mehta203cc962016-04-07 15:25:43 +0530231 }, as_dict=as_dict)
Saurabh02875592013-07-08 18:45:55 +0530232
Himanshud94a38e2020-05-18 14:26:26 +0530233
Saurabh022ab632017-11-10 15:06:02 +0530234def bom(doctype, txt, searchfield, start, page_len, filters):
Anand Doshibd67e872014-04-11 16:51:27 +0530235 conditions = []
Himanshud94a38e2020-05-18 14:26:26 +0530236 fields = get_fields("BOM", ["name", "item"])
Saurabhf52dc072013-07-10 13:07:49 +0530237
Himanshud94a38e2020-05-18 14:26:26 +0530238 return frappe.db.sql("""select {fields}
Anand Doshibd67e872014-04-11 16:51:27 +0530239 from tabBOM
240 where tabBOM.docstatus=1
241 and tabBOM.is_active=1
Nabin Hait62211172016-03-16 16:22:03 +0530242 and tabBOM.`{key}` like %(txt)s
243 {fcond} {mcond}
244 order by
Rushabh Mehta3574b372016-03-11 14:33:04 +0530245 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
246 idx desc, name
Nabin Hait62211172016-03-16 16:22:03 +0530247 limit %(start)s, %(page_len)s """.format(
Himanshud94a38e2020-05-18 14:26:26 +0530248 fields=", ".join(fields),
Mangesh-Khairnar6a796912019-07-08 10:40:40 +0530249 fcond=get_filters_cond(doctype, filters, conditions).replace('%', '%%'),
Karthikeyan S747c2622019-07-19 22:49:21 +0530250 mcond=get_match_cond(doctype).replace('%', '%%'),
251 key=searchfield),
Mangesh-Khairnar6a796912019-07-08 10:40:40 +0530252 {
Karthikeyan S747c2622019-07-19 22:49:21 +0530253 'txt': '%' + txt + '%',
Rushabh Mehta3574b372016-03-11 14:33:04 +0530254 '_txt': txt.replace("%", ""),
Saurabh022ab632017-11-10 15:06:02 +0530255 'start': start or 0,
256 'page_len': page_len or 20
Rushabh Mehta3574b372016-03-11 14:33:04 +0530257 })
Saurabh02875592013-07-08 18:45:55 +0530258
Himanshud94a38e2020-05-18 14:26:26 +0530259
Saurabh02875592013-07-08 18:45:55 +0530260def get_project_name(doctype, txt, searchfield, start, page_len, filters):
261 cond = ''
Nabin Haitf71011a2014-08-21 11:34:31 +0530262 if filters.get('customer'):
Suraj Shetty6ea3de92018-09-26 18:15:53 +0530263 cond = """(`tabProject`.customer = %s or
rohitwaghchauree3304722018-08-27 11:43:57 +0530264 ifnull(`tabProject`.customer,"")="") and""" %(frappe.db.escape(filters.get("customer")))
Anand Doshibd67e872014-04-11 16:51:27 +0530265
Himanshud94a38e2020-05-18 14:26:26 +0530266 fields = get_fields("Project", ["name"])
267
268 return frappe.db.sql("""select {fields} from `tabProject`
Anand Doshibd67e872014-04-11 16:51:27 +0530269 where `tabProject`.status not in ("Completed", "Cancelled")
Rushabh Mehta3574b372016-03-11 14:33:04 +0530270 and {cond} `tabProject`.name like %(txt)s {match_cond}
271 order by
272 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
273 idx desc,
274 `tabProject`.name asc
275 limit {start}, {page_len}""".format(
Himanshud94a38e2020-05-18 14:26:26 +0530276 fields=", ".join(['`tabProject`.{0}'.format(f) for f in fields]),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530277 cond=cond,
278 match_cond=get_match_cond(doctype),
279 start=start,
280 page_len=page_len), {
281 "txt": "%{0}%".format(txt),
Nabin Haitdf4deba2016-03-16 11:16:31 +0530282 "_txt": txt.replace('%', '')
Rushabh Mehta3574b372016-03-11 14:33:04 +0530283 })
Anand Doshibd67e872014-04-11 16:51:27 +0530284
tundebabzyf6d738b2017-09-18 12:40:09 +0100285
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530286def get_delivery_notes_to_be_billed(doctype, txt, searchfield, start, page_len, filters, as_dict):
Himanshud94a38e2020-05-18 14:26:26 +0530287 fields = get_fields("Delivery Note", ["name", "customer", "posting_date"])
288
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530289 return frappe.db.sql("""
Himanshud94a38e2020-05-18 14:26:26 +0530290 select %(fields)s
Anand Doshibd67e872014-04-11 16:51:27 +0530291 from `tabDelivery Note`
292 where `tabDelivery Note`.`%(key)s` like %(txt)s and
tundebabzyf6d738b2017-09-18 12:40:09 +0100293 `tabDelivery Note`.docstatus = 1
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530294 and status not in ("Stopped", "Closed") %(fcond)s
tundebabzyf6d738b2017-09-18 12:40:09 +0100295 and (
296 (`tabDelivery Note`.is_return = 0 and `tabDelivery Note`.per_billed < 100)
297 or `tabDelivery Note`.grand_total = 0
298 or (
299 `tabDelivery Note`.is_return = 1
300 and return_against in (select name from `tabDelivery Note` where per_billed < 100)
301 )
302 )
rohitwaghchaured07a3e12019-05-15 07:46:28 +0530303 %(mcond)s order by `tabDelivery Note`.`%(key)s` asc limit %(start)s, %(page_len)s
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530304 """ % {
Himanshud94a38e2020-05-18 14:26:26 +0530305 "fields": ", ".join(["`tabDelivery Note`.{0}".format(f) for f in fields]),
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530306 "key": searchfield,
307 "fcond": get_filters_cond(doctype, filters, []),
308 "mcond": get_match_cond(doctype),
rohitwaghchaured07a3e12019-05-15 07:46:28 +0530309 "start": start,
310 "page_len": page_len,
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530311 "txt": "%(txt)s"
tundebabzyf6d738b2017-09-18 12:40:09 +0100312 }, {"txt": ("%%%s%%" % txt)}, as_dict=as_dict)
313
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530314
315def get_batch_no(doctype, txt, searchfield, start, page_len, filters):
Neil Trini Lasradoebb60f52015-07-08 14:36:09 +0530316 cond = ""
317 if filters.get("posting_date"):
Nabin Hait7918b922018-01-31 15:30:03 +0530318 cond = "and (batch.expiry_date is null or batch.expiry_date >= %(posting_date)s)"
Rushabh Mehtab6398be2015-08-26 10:50:16 +0530319
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530320 batch_nos = None
321 args = {
322 'item_code': filters.get("item_code"),
323 'warehouse': filters.get("warehouse"),
324 'posting_date': filters.get('posting_date'),
Anand Doshi0dc79f42015-04-06 12:59:34 +0530325 'txt': "%{0}%".format(txt),
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530326 "start": start,
327 "page_len": page_len
328 }
329
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530330 having_clause = "having sum(sle.actual_qty) > 0"
331 if filters.get("is_return"):
332 having_clause = ""
333
Anand Doshi0dc79f42015-04-06 12:59:34 +0530334 if args.get('warehouse'):
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530335 batch_nos = frappe.db.sql("""select sle.batch_no, round(sum(sle.actual_qty),2), sle.stock_uom,
336 concat('MFG-',batch.manufacturing_date), concat('EXP-',batch.expiry_date)
337 from `tabStock Ledger Entry` sle
338 INNER JOIN `tabBatch` batch on sle.batch_no = batch.name
339 where
340 batch.disabled = 0
341 and sle.item_code = %(item_code)s
342 and sle.warehouse = %(warehouse)s
343 and (sle.batch_no like %(txt)s
Sun Howwrongbum088be372019-12-24 12:29:25 +0530344 or batch.expiry_date like %(txt)s
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530345 or batch.manufacturing_date like %(txt)s)
346 and batch.docstatus < 2
347 {cond}
348 {match_conditions}
349 group by batch_no {having_clause}
350 order by batch.expiry_date, sle.batch_no desc
351 limit %(start)s, %(page_len)s""".format(
352 cond=cond,
353 match_conditions=get_match_cond(doctype),
354 having_clause = having_clause
355 ), args)
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530356
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530357 return batch_nos
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530358 else:
sivankar621740e2018-02-12 14:33:40 +0530359 return frappe.db.sql("""select name, concat('MFG-', manufacturing_date), concat('EXP-',expiry_date) from `tabBatch` batch
Doridel Cahanap59e4c322018-08-06 17:15:18 +0800360 where batch.disabled = 0
361 and item = %(item_code)s
sivankar621740e2018-02-12 14:33:40 +0530362 and (name like %(txt)s
Sun Howwrongbum088be372019-12-24 12:29:25 +0530363 or expiry_date like %(txt)s
sivankar621740e2018-02-12 14:33:40 +0530364 or manufacturing_date like %(txt)s)
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530365 and docstatus < 2
Neil Trini Lasradoebb60f52015-07-08 14:36:09 +0530366 {0}
Anand Doshi0dc79f42015-04-06 12:59:34 +0530367 {match_conditions}
368 order by expiry_date, name desc
Nabin Haite52ee552015-09-02 10:55:32 +0530369 limit %(start)s, %(page_len)s""".format(cond, match_conditions=get_match_cond(doctype)), args)
Nabin Haitea4aa042014-05-28 12:56:28 +0530370
Himanshud94a38e2020-05-18 14:26:26 +0530371
Nabin Haitea4aa042014-05-28 12:56:28 +0530372def get_account_list(doctype, txt, searchfield, start, page_len, filters):
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530373 filter_list = []
Nabin Haitea4aa042014-05-28 12:56:28 +0530374
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530375 if isinstance(filters, dict):
376 for key, val in filters.items():
377 if isinstance(val, (list, tuple)):
378 filter_list.append([doctype, key, val[0], val[1]])
379 else:
380 filter_list.append([doctype, key, "=", val])
bhupeshg2e2e973f2015-04-14 22:15:24 +0530381 elif isinstance(filters, list):
382 filter_list.extend(filters)
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530383
Rushabh Mehta38c6b522015-04-23 13:14:17 +0530384 if "is_group" not in [d[1] for d in filter_list]:
385 filter_list.append(["Account", "is_group", "=", "0"])
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530386
387 if searchfield and txt:
388 filter_list.append([doctype, searchfield, "like", "%%%s%%" % txt])
389
Rushabh Mehtac0bb4532014-09-09 16:15:35 +0530390 return frappe.desk.reportview.execute("Account", filters = filter_list,
Nabin Haitea4aa042014-05-28 12:56:28 +0530391 fields = ["name", "parent_account"],
392 limit_start=start, limit_page_length=page_len, as_list=True)
Anand Doshifaefeaa2014-06-24 18:53:04 +0530393
Maricaac98eb52020-04-28 13:00:44 +0530394def get_blanket_orders(doctype, txt, searchfield, start, page_len, filters):
395 return frappe.db.sql("""select distinct bo.name, bo.blanket_order_type, bo.to_date
396 from `tabBlanket Order` bo, `tabBlanket Order Item` boi
397 where
398 boi.parent = bo.name
399 and boi.item_code = {item_code}
400 and bo.blanket_order_type = '{blanket_order_type}'
401 and bo.company = {company}
402 and bo.docstatus = 1"""
403 .format(item_code = frappe.db.escape(filters.get("item")),
404 blanket_order_type = filters.get("blanket_order_type"),
405 company = frappe.db.escape(filters.get("company"))
406 ))
Nabin Haitafd14f62015-10-19 11:55:28 +0530407
Marica299e2172020-04-28 13:00:04 +0530408def get_blanket_orders(doctype, txt, searchfield, start, page_len, filters):
409 return frappe.db.sql("""select distinct bo.name, bo.blanket_order_type, bo.to_date
410 from `tabBlanket Order` bo, `tabBlanket Order Item` boi
411 where
412 boi.parent = bo.name
413 and boi.item_code = {item_code}
414 and bo.blanket_order_type = '{blanket_order_type}'
415 and bo.company = {company}
416 and bo.docstatus = 1"""
417 .format(item_code = frappe.db.escape(filters.get("item")),
418 blanket_order_type = filters.get("blanket_order_type"),
419 company = frappe.db.escape(filters.get("company"))
420 ))
Nabin Haitafd14f62015-10-19 11:55:28 +0530421
Himanshud94a38e2020-05-18 14:26:26 +0530422
Nabin Haitafd14f62015-10-19 11:55:28 +0530423@frappe.whitelist()
424def get_income_account(doctype, txt, searchfield, start, page_len, filters):
425 from erpnext.controllers.queries import get_match_cond
426
427 # income account can be any Credit account,
428 # but can also be a Asset account with account_type='Income Account' in special circumstances.
429 # Hence the first condition is an "OR"
430 if not filters: filters = {}
431
Anand Doshi21e09a22015-10-29 12:21:41 +0530432 condition = ""
Nabin Haitafd14f62015-10-19 11:55:28 +0530433 if filters.get("company"):
434 condition += "and tabAccount.company = %(company)s"
Anand Doshi21e09a22015-10-29 12:21:41 +0530435
Nabin Haitafd14f62015-10-19 11:55:28 +0530436 return frappe.db.sql("""select tabAccount.name from `tabAccount`
437 where (tabAccount.report_type = "Profit and Loss"
438 or tabAccount.account_type in ("Income Account", "Temporary"))
439 and tabAccount.is_group=0
440 and tabAccount.`{key}` LIKE %(txt)s
Rushabh Mehta3574b372016-03-11 14:33:04 +0530441 {condition} {match_condition}
442 order by idx desc, name"""
Nabin Haitafd14f62015-10-19 11:55:28 +0530443 .format(condition=condition, match_condition=get_match_cond(doctype), key=searchfield), {
Suraj Shetty4b404c42018-09-27 15:39:34 +0530444 'txt': '%' + txt + '%',
Nabin Haitafd14f62015-10-19 11:55:28 +0530445 'company': filters.get("company", "")
Anand Doshi21e09a22015-10-29 12:21:41 +0530446 })
Nabin Hait3a15c922016-03-04 12:30:46 +0530447
448
449@frappe.whitelist()
450def get_expense_account(doctype, txt, searchfield, start, page_len, filters):
451 from erpnext.controllers.queries import get_match_cond
Rushabh Mehta203cc962016-04-07 15:25:43 +0530452
Nabin Hait3a15c922016-03-04 12:30:46 +0530453 if not filters: filters = {}
454
455 condition = ""
456 if filters.get("company"):
457 condition += "and tabAccount.company = %(company)s"
Rushabh Mehta203cc962016-04-07 15:25:43 +0530458
Nabin Hait3a15c922016-03-04 12:30:46 +0530459 return frappe.db.sql("""select tabAccount.name from `tabAccount`
460 where (tabAccount.report_type = "Profit and Loss"
Mangesh-Khairnar5619db22019-08-21 14:49:24 +0530461 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 +0530462 and tabAccount.is_group=0
463 and tabAccount.docstatus!=2
464 and tabAccount.{key} LIKE %(txt)s
465 {condition} {match_condition}"""
Suraj Shettybfc195d2018-09-21 10:20:52 +0530466 .format(condition=condition, key=searchfield,
Nabin Hait3a15c922016-03-04 12:30:46 +0530467 match_condition=get_match_cond(doctype)), {
Neil Trini Lasrado30b97b02016-03-31 23:10:13 +0530468 'company': filters.get("company", ""),
Suraj Shetty4b404c42018-09-27 15:39:34 +0530469 'txt': '%' + txt + '%'
Maxwell Morais35572612016-07-21 23:42:59 -0300470 })
suyashphadtare049a88c2017-01-12 17:49:37 +0530471
472
473@frappe.whitelist()
474def warehouse_query(doctype, txt, searchfield, start, page_len, filters):
475 # Should be used when item code is passed in filters.
suyashphadtare750a0672017-01-18 15:35:01 +0530476 conditions, bin_conditions = [], []
477 filter_dict = get_doctype_wise_filters(filters)
478
479 sub_query = """ select round(`tabBin`.actual_qty, 2) from `tabBin`
suyashphadtare34ab1362017-01-31 15:14:44 +0530480 where `tabBin`.warehouse = `tabWarehouse`.name
481 {bin_conditions} """.format(
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530482 bin_conditions=get_filters_cond(doctype, filter_dict.get("Bin"),
Nabin Hait4e6ff8c2017-05-09 15:09:10 +0530483 bin_conditions, ignore_permissions=True))
suyashphadtare750a0672017-01-18 15:35:01 +0530484
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530485 query = """select `tabWarehouse`.name,
suyashphadtare34ab1362017-01-31 15:14:44 +0530486 CONCAT_WS(" : ", "Actual Qty", ifnull( ({sub_query}), 0) ) as actual_qty
487 from `tabWarehouse`
488 where
Suraj Shetty6ea3de92018-09-26 18:15:53 +0530489 `tabWarehouse`.`{key}` like {txt}
suyashphadtare34ab1362017-01-31 15:14:44 +0530490 {fcond} {mcond}
491 order by
492 `tabWarehouse`.name desc
493 limit
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530494 {start}, {page_len}
suyashphadtare34ab1362017-01-31 15:14:44 +0530495 """.format(
496 sub_query=sub_query,
Suraj Shettybfc195d2018-09-21 10:20:52 +0530497 key=searchfield,
suyashphadtare34ab1362017-01-31 15:14:44 +0530498 fcond=get_filters_cond(doctype, filter_dict.get("Warehouse"), conditions),
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530499 mcond=get_match_cond(doctype),
500 start=start,
501 page_len=page_len,
502 txt=frappe.db.escape('%{0}%'.format(txt))
503 )
504
505 return frappe.db.sql(query)
suyashphadtare750a0672017-01-18 15:35:01 +0530506
507
508def get_doctype_wise_filters(filters):
509 # Helper function to seperate filters doctype_wise
510 filter_dict = defaultdict(list)
511 for row in filters:
512 filter_dict[row[0]].append(row)
513 return filter_dict
tundebabzy2a4fefc2017-11-29 06:23:09 +0100514
515
516@frappe.whitelist()
517def get_batch_numbers(doctype, txt, searchfield, start, page_len, filters):
rohitwaghchaure9fbed562018-01-12 16:22:33 +0530518 query = """select batch_id from `tabBatch`
Doridel Cahanap59e4c322018-08-06 17:15:18 +0800519 where disabled = 0
520 and (expiry_date >= CURDATE() or expiry_date IS NULL)
Suraj Shettybfc195d2018-09-21 10:20:52 +0530521 and name like {txt}""".format(txt = frappe.db.escape('%{0}%'.format(txt)))
tundebabzy2a4fefc2017-11-29 06:23:09 +0100522
rohitwaghchaure9fbed562018-01-12 16:22:33 +0530523 if filters and filters.get('item'):
Suraj Shettybfc195d2018-09-21 10:20:52 +0530524 query += " and item = {item}".format(item = frappe.db.escape(filters.get('item')))
tundebabzy2a4fefc2017-11-29 06:23:09 +0100525
Sachin Mane64f48db2018-01-08 17:57:32 +0530526 return frappe.db.sql(query, filters)
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530527
Himanshud94a38e2020-05-18 14:26:26 +0530528
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530529@frappe.whitelist()
530def item_manufacturer_query(doctype, txt, searchfield, start, page_len, filters):
Maricabac4b932019-09-16 19:44:28 +0530531 item_filters = [
532 ['manufacturer', 'like', '%' + txt + '%'],
533 ['item_code', '=', filters.get("item_code")]
534 ]
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530535
Maricabac4b932019-09-16 19:44:28 +0530536 item_manufacturers = frappe.get_all(
537 "Item Manufacturer",
538 fields=["manufacturer", "manufacturer_part_no"],
539 filters=item_filters,
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530540 limit_start=start,
541 limit_page_length=page_len,
542 as_list=1
543 )
Maricabac4b932019-09-16 19:44:28 +0530544 return item_manufacturers
Saqibd9956092019-11-18 11:46:55 +0530545
Himanshud94a38e2020-05-18 14:26:26 +0530546
Saqibd9956092019-11-18 11:46:55 +0530547@frappe.whitelist()
548def get_purchase_receipts(doctype, txt, searchfield, start, page_len, filters):
549 query = """
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530550 select pr.name
Saqibd9956092019-11-18 11:46:55 +0530551 from `tabPurchase Receipt` pr, `tabPurchase Receipt Item` pritem
552 where pr.docstatus = 1 and pritem.parent = pr.name
553 and pr.name like {txt}""".format(txt = frappe.db.escape('%{0}%'.format(txt)))
554
555 if filters and filters.get('item_code'):
556 query += " and pritem.item_code = {item_code}".format(item_code = frappe.db.escape(filters.get('item_code')))
557
558 return frappe.db.sql(query, filters)
559
Himanshud94a38e2020-05-18 14:26:26 +0530560
Saqibd9956092019-11-18 11:46:55 +0530561@frappe.whitelist()
562def get_purchase_invoices(doctype, txt, searchfield, start, page_len, filters):
563 query = """
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530564 select pi.name
Saqibd9956092019-11-18 11:46:55 +0530565 from `tabPurchase Invoice` pi, `tabPurchase Invoice Item` piitem
566 where pi.docstatus = 1 and piitem.parent = pi.name
567 and pi.name like {txt}""".format(txt = frappe.db.escape('%{0}%'.format(txt)))
568
569 if filters and filters.get('item_code'):
570 query += " and piitem.item_code = {item_code}".format(item_code = frappe.db.escape(filters.get('item_code')))
571
572 return frappe.db.sql(query, filters)
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530573
Himanshud94a38e2020-05-18 14:26:26 +0530574
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530575@frappe.whitelist()
576def get_tax_template(doctype, txt, searchfield, start, page_len, filters):
577
578 item_doc = frappe.get_cached_doc('Item', filters.get('item_code'))
579 item_group = filters.get('item_group')
580 taxes = item_doc.taxes or []
581
582 while item_group:
583 item_group_doc = frappe.get_cached_doc('Item Group', item_group)
584 taxes += item_group_doc.taxes or []
585 item_group = item_group_doc.parent_item_group
586
587 if not taxes:
588 return frappe.db.sql(""" SELECT name FROM `tabItem Tax Template` """)
589 else:
590 args = {
591 'item_code': filters.get('item_code'),
592 'posting_date': filters.get('valid_from'),
593 'tax_category': filters.get('tax_category')
594 }
595
596 taxes = _get_item_tax_template(args, taxes, for_validate=True)
597 return [(d,) for d in set(taxes)]
Himanshud94a38e2020-05-18 14:26:26 +0530598
599
600def get_fields(doctype, fields=[]):
601 meta = frappe.get_meta(doctype)
602 fields.extend(meta.get_search_fields())
603
604 if meta.title_field and not meta.title_field.strip() in fields:
605 fields.insert(1, meta.title_field.strip())
606
607 return unique(fields)