blob: ee8364a40e3a861d047c868413e2bc281a3e7443 [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
Prateeksha Singh984a7a72018-05-17 17:29:36 +0530191 return frappe.db.sql("""select tabItem.name,
Anand Doshibd67e872014-04-11 16:51:27 +0530192 if(length(tabItem.item_name) > 40,
193 concat(substr(tabItem.item_name, 1, 40), "..."), item_name) as item_name,
Prateeksha Singh984a7a72018-05-17 17:29:36 +0530194 tabItem.item_group,
Saurabh02875592013-07-08 18:45:55 +0530195 if(length(tabItem.description) > 40, \
Rohit Waghchaurec42312e2019-11-19 19:05:23 +0530196 concat(substr(tabItem.description, 1, 40), "..."), description) as description
marination1e754b12019-10-30 18:33:44 +0530197 {columns}
Anand Doshibd67e872014-04-11 16:51:27 +0530198 from tabItem
Anand Doshi22c0d782013-11-04 16:23:04 +0530199 where tabItem.docstatus < 2
Anand Doshi21e09a22015-10-29 12:21:41 +0530200 and tabItem.disabled=0
rohitwaghchaure79789072020-05-21 18:10:13 +0530201 and tabItem.has_variants=0
Rushabh Mehta864d1ea2014-06-23 12:20:12 +0530202 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 +0530203 and ({scond} or tabItem.item_code IN (select parent from `tabItem Barcode` where barcode LIKE %(txt)s)
Rohit Waghchaure2bfb0632019-03-02 21:47:55 +0530204 {description_cond})
Anand Doshi22c0d782013-11-04 16:23:04 +0530205 {fcond} {mcond}
Anand Doshi652bc072014-04-16 15:21:46 +0530206 order by
207 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
208 if(locate(%(_txt)s, item_name), locate(%(_txt)s, item_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530209 idx desc,
Anand Doshi652bc072014-04-16 15:21:46 +0530210 name, item_name
Rushabh Mehtabc4e2cd2017-10-17 12:30:34 +0530211 limit %(start)s, %(page_len)s """.format(
212 key=searchfield,
marination1e754b12019-10-30 18:33:44 +0530213 columns=columns,
marination3dbef9d2019-10-28 15:48:10 +0530214 scond=searchfields,
Nabin Haitc6285062016-03-30 13:10:25 +0530215 fcond=get_filters_cond(doctype, filters, conditions).replace('%', '%%'),
Rushabh Mehtad5f9ebd2018-04-02 23:37:33 +0530216 mcond=get_match_cond(doctype).replace('%', '%%'),
217 description_cond = description_cond),
Anand Doshi22c0d782013-11-04 16:23:04 +0530218 {
219 "today": nowdate(),
220 "txt": "%%%s%%" % txt,
Anand Doshi652bc072014-04-16 15:21:46 +0530221 "_txt": txt.replace("%", ""),
Anand Doshi22c0d782013-11-04 16:23:04 +0530222 "start": start,
223 "page_len": page_len
Rushabh Mehta203cc962016-04-07 15:25:43 +0530224 }, as_dict=as_dict)
Saurabh02875592013-07-08 18:45:55 +0530225
Himanshud94a38e2020-05-18 14:26:26 +0530226
Saurabh022ab632017-11-10 15:06:02 +0530227def bom(doctype, txt, searchfield, start, page_len, filters):
Anand Doshibd67e872014-04-11 16:51:27 +0530228 conditions = []
Himanshud94a38e2020-05-18 14:26:26 +0530229 fields = get_fields("BOM", ["name", "item"])
Saurabhf52dc072013-07-10 13:07:49 +0530230
Himanshud94a38e2020-05-18 14:26:26 +0530231 return frappe.db.sql("""select {fields}
Anand Doshibd67e872014-04-11 16:51:27 +0530232 from tabBOM
233 where tabBOM.docstatus=1
234 and tabBOM.is_active=1
Nabin Hait62211172016-03-16 16:22:03 +0530235 and tabBOM.`{key}` like %(txt)s
236 {fcond} {mcond}
237 order by
Rushabh Mehta3574b372016-03-11 14:33:04 +0530238 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
239 idx desc, name
Nabin Hait62211172016-03-16 16:22:03 +0530240 limit %(start)s, %(page_len)s """.format(
Himanshud94a38e2020-05-18 14:26:26 +0530241 fields=", ".join(fields),
Mangesh-Khairnar6a796912019-07-08 10:40:40 +0530242 fcond=get_filters_cond(doctype, filters, conditions).replace('%', '%%'),
Karthikeyan S747c2622019-07-19 22:49:21 +0530243 mcond=get_match_cond(doctype).replace('%', '%%'),
244 key=searchfield),
Mangesh-Khairnar6a796912019-07-08 10:40:40 +0530245 {
Karthikeyan S747c2622019-07-19 22:49:21 +0530246 'txt': '%' + txt + '%',
Rushabh Mehta3574b372016-03-11 14:33:04 +0530247 '_txt': txt.replace("%", ""),
Saurabh022ab632017-11-10 15:06:02 +0530248 'start': start or 0,
249 'page_len': page_len or 20
Rushabh Mehta3574b372016-03-11 14:33:04 +0530250 })
Saurabh02875592013-07-08 18:45:55 +0530251
Himanshud94a38e2020-05-18 14:26:26 +0530252
Saurabh02875592013-07-08 18:45:55 +0530253def get_project_name(doctype, txt, searchfield, start, page_len, filters):
254 cond = ''
Nabin Haitf71011a2014-08-21 11:34:31 +0530255 if filters.get('customer'):
Suraj Shetty6ea3de92018-09-26 18:15:53 +0530256 cond = """(`tabProject`.customer = %s or
rohitwaghchauree3304722018-08-27 11:43:57 +0530257 ifnull(`tabProject`.customer,"")="") and""" %(frappe.db.escape(filters.get("customer")))
Anand Doshibd67e872014-04-11 16:51:27 +0530258
Himanshud94a38e2020-05-18 14:26:26 +0530259 fields = get_fields("Project", ["name"])
260
261 return frappe.db.sql("""select {fields} from `tabProject`
Anand Doshibd67e872014-04-11 16:51:27 +0530262 where `tabProject`.status not in ("Completed", "Cancelled")
Rushabh Mehta3574b372016-03-11 14:33:04 +0530263 and {cond} `tabProject`.name like %(txt)s {match_cond}
264 order by
265 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
266 idx desc,
267 `tabProject`.name asc
268 limit {start}, {page_len}""".format(
Himanshud94a38e2020-05-18 14:26:26 +0530269 fields=", ".join(['`tabProject`.{0}'.format(f) for f in fields]),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530270 cond=cond,
271 match_cond=get_match_cond(doctype),
272 start=start,
273 page_len=page_len), {
274 "txt": "%{0}%".format(txt),
Nabin Haitdf4deba2016-03-16 11:16:31 +0530275 "_txt": txt.replace('%', '')
Rushabh Mehta3574b372016-03-11 14:33:04 +0530276 })
Anand Doshibd67e872014-04-11 16:51:27 +0530277
tundebabzyf6d738b2017-09-18 12:40:09 +0100278
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530279def get_delivery_notes_to_be_billed(doctype, txt, searchfield, start, page_len, filters, as_dict):
Himanshud94a38e2020-05-18 14:26:26 +0530280 fields = get_fields("Delivery Note", ["name", "customer", "posting_date"])
281
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530282 return frappe.db.sql("""
Himanshud94a38e2020-05-18 14:26:26 +0530283 select %(fields)s
Anand Doshibd67e872014-04-11 16:51:27 +0530284 from `tabDelivery Note`
285 where `tabDelivery Note`.`%(key)s` like %(txt)s and
tundebabzyf6d738b2017-09-18 12:40:09 +0100286 `tabDelivery Note`.docstatus = 1
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530287 and status not in ("Stopped", "Closed") %(fcond)s
tundebabzyf6d738b2017-09-18 12:40:09 +0100288 and (
289 (`tabDelivery Note`.is_return = 0 and `tabDelivery Note`.per_billed < 100)
290 or `tabDelivery Note`.grand_total = 0
291 or (
292 `tabDelivery Note`.is_return = 1
293 and return_against in (select name from `tabDelivery Note` where per_billed < 100)
294 )
295 )
rohitwaghchaured07a3e12019-05-15 07:46:28 +0530296 %(mcond)s order by `tabDelivery Note`.`%(key)s` asc limit %(start)s, %(page_len)s
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530297 """ % {
Himanshud94a38e2020-05-18 14:26:26 +0530298 "fields": ", ".join(["`tabDelivery Note`.{0}".format(f) for f in fields]),
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530299 "key": searchfield,
300 "fcond": get_filters_cond(doctype, filters, []),
301 "mcond": get_match_cond(doctype),
rohitwaghchaured07a3e12019-05-15 07:46:28 +0530302 "start": start,
303 "page_len": page_len,
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530304 "txt": "%(txt)s"
tundebabzyf6d738b2017-09-18 12:40:09 +0100305 }, {"txt": ("%%%s%%" % txt)}, as_dict=as_dict)
306
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530307
308def get_batch_no(doctype, txt, searchfield, start, page_len, filters):
Neil Trini Lasradoebb60f52015-07-08 14:36:09 +0530309 cond = ""
310 if filters.get("posting_date"):
Nabin Hait7918b922018-01-31 15:30:03 +0530311 cond = "and (batch.expiry_date is null or batch.expiry_date >= %(posting_date)s)"
Rushabh Mehtab6398be2015-08-26 10:50:16 +0530312
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530313 batch_nos = None
314 args = {
315 'item_code': filters.get("item_code"),
316 'warehouse': filters.get("warehouse"),
317 'posting_date': filters.get('posting_date'),
Anand Doshi0dc79f42015-04-06 12:59:34 +0530318 'txt': "%{0}%".format(txt),
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530319 "start": start,
320 "page_len": page_len
321 }
322
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530323 having_clause = "having sum(sle.actual_qty) > 0"
324 if filters.get("is_return"):
325 having_clause = ""
326
Anand Doshi0dc79f42015-04-06 12:59:34 +0530327 if args.get('warehouse'):
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530328 batch_nos = frappe.db.sql("""select sle.batch_no, round(sum(sle.actual_qty),2), sle.stock_uom,
329 concat('MFG-',batch.manufacturing_date), concat('EXP-',batch.expiry_date)
330 from `tabStock Ledger Entry` sle
331 INNER JOIN `tabBatch` batch on sle.batch_no = batch.name
332 where
333 batch.disabled = 0
334 and sle.item_code = %(item_code)s
335 and sle.warehouse = %(warehouse)s
336 and (sle.batch_no like %(txt)s
Sun Howwrongbum088be372019-12-24 12:29:25 +0530337 or batch.expiry_date like %(txt)s
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530338 or batch.manufacturing_date like %(txt)s)
339 and batch.docstatus < 2
340 {cond}
341 {match_conditions}
342 group by batch_no {having_clause}
343 order by batch.expiry_date, sle.batch_no desc
344 limit %(start)s, %(page_len)s""".format(
345 cond=cond,
346 match_conditions=get_match_cond(doctype),
347 having_clause = having_clause
348 ), args)
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530349
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530350 return batch_nos
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530351 else:
sivankar621740e2018-02-12 14:33:40 +0530352 return frappe.db.sql("""select name, concat('MFG-', manufacturing_date), concat('EXP-',expiry_date) from `tabBatch` batch
Doridel Cahanap59e4c322018-08-06 17:15:18 +0800353 where batch.disabled = 0
354 and item = %(item_code)s
sivankar621740e2018-02-12 14:33:40 +0530355 and (name like %(txt)s
Sun Howwrongbum088be372019-12-24 12:29:25 +0530356 or expiry_date like %(txt)s
sivankar621740e2018-02-12 14:33:40 +0530357 or manufacturing_date like %(txt)s)
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530358 and docstatus < 2
Neil Trini Lasradoebb60f52015-07-08 14:36:09 +0530359 {0}
Anand Doshi0dc79f42015-04-06 12:59:34 +0530360 {match_conditions}
361 order by expiry_date, name desc
Nabin Haite52ee552015-09-02 10:55:32 +0530362 limit %(start)s, %(page_len)s""".format(cond, match_conditions=get_match_cond(doctype)), args)
Nabin Haitea4aa042014-05-28 12:56:28 +0530363
Himanshud94a38e2020-05-18 14:26:26 +0530364
Nabin Haitea4aa042014-05-28 12:56:28 +0530365def get_account_list(doctype, txt, searchfield, start, page_len, filters):
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530366 filter_list = []
Nabin Haitea4aa042014-05-28 12:56:28 +0530367
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530368 if isinstance(filters, dict):
369 for key, val in filters.items():
370 if isinstance(val, (list, tuple)):
371 filter_list.append([doctype, key, val[0], val[1]])
372 else:
373 filter_list.append([doctype, key, "=", val])
bhupeshg2e2e973f2015-04-14 22:15:24 +0530374 elif isinstance(filters, list):
375 filter_list.extend(filters)
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530376
Rushabh Mehta38c6b522015-04-23 13:14:17 +0530377 if "is_group" not in [d[1] for d in filter_list]:
378 filter_list.append(["Account", "is_group", "=", "0"])
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530379
380 if searchfield and txt:
381 filter_list.append([doctype, searchfield, "like", "%%%s%%" % txt])
382
Rushabh Mehtac0bb4532014-09-09 16:15:35 +0530383 return frappe.desk.reportview.execute("Account", filters = filter_list,
Nabin Haitea4aa042014-05-28 12:56:28 +0530384 fields = ["name", "parent_account"],
385 limit_start=start, limit_page_length=page_len, as_list=True)
Anand Doshifaefeaa2014-06-24 18:53:04 +0530386
Himanshud94a38e2020-05-18 14:26:26 +0530387
Marica299e2172020-04-28 13:00:04 +0530388def get_blanket_orders(doctype, txt, searchfield, start, page_len, filters):
389 return frappe.db.sql("""select distinct bo.name, bo.blanket_order_type, bo.to_date
390 from `tabBlanket Order` bo, `tabBlanket Order Item` boi
391 where
392 boi.parent = bo.name
393 and boi.item_code = {item_code}
394 and bo.blanket_order_type = '{blanket_order_type}'
395 and bo.company = {company}
396 and bo.docstatus = 1"""
397 .format(item_code = frappe.db.escape(filters.get("item")),
398 blanket_order_type = filters.get("blanket_order_type"),
399 company = frappe.db.escape(filters.get("company"))
400 ))
Nabin Haitafd14f62015-10-19 11:55:28 +0530401
Himanshud94a38e2020-05-18 14:26:26 +0530402
Nabin Haitafd14f62015-10-19 11:55:28 +0530403@frappe.whitelist()
404def get_income_account(doctype, txt, searchfield, start, page_len, filters):
405 from erpnext.controllers.queries import get_match_cond
406
407 # income account can be any Credit account,
408 # but can also be a Asset account with account_type='Income Account' in special circumstances.
409 # Hence the first condition is an "OR"
410 if not filters: filters = {}
411
Anand Doshi21e09a22015-10-29 12:21:41 +0530412 condition = ""
Nabin Haitafd14f62015-10-19 11:55:28 +0530413 if filters.get("company"):
414 condition += "and tabAccount.company = %(company)s"
Anand Doshi21e09a22015-10-29 12:21:41 +0530415
Nabin Haitafd14f62015-10-19 11:55:28 +0530416 return frappe.db.sql("""select tabAccount.name from `tabAccount`
417 where (tabAccount.report_type = "Profit and Loss"
418 or tabAccount.account_type in ("Income Account", "Temporary"))
419 and tabAccount.is_group=0
420 and tabAccount.`{key}` LIKE %(txt)s
Rushabh Mehta3574b372016-03-11 14:33:04 +0530421 {condition} {match_condition}
422 order by idx desc, name"""
Nabin Haitafd14f62015-10-19 11:55:28 +0530423 .format(condition=condition, match_condition=get_match_cond(doctype), key=searchfield), {
Suraj Shetty4b404c42018-09-27 15:39:34 +0530424 'txt': '%' + txt + '%',
Nabin Haitafd14f62015-10-19 11:55:28 +0530425 'company': filters.get("company", "")
Anand Doshi21e09a22015-10-29 12:21:41 +0530426 })
Nabin Hait3a15c922016-03-04 12:30:46 +0530427
428
429@frappe.whitelist()
430def get_expense_account(doctype, txt, searchfield, start, page_len, filters):
431 from erpnext.controllers.queries import get_match_cond
Rushabh Mehta203cc962016-04-07 15:25:43 +0530432
Nabin Hait3a15c922016-03-04 12:30:46 +0530433 if not filters: filters = {}
434
435 condition = ""
436 if filters.get("company"):
437 condition += "and tabAccount.company = %(company)s"
Rushabh Mehta203cc962016-04-07 15:25:43 +0530438
Nabin Hait3a15c922016-03-04 12:30:46 +0530439 return frappe.db.sql("""select tabAccount.name from `tabAccount`
440 where (tabAccount.report_type = "Profit and Loss"
Mangesh-Khairnar5619db22019-08-21 14:49:24 +0530441 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 +0530442 and tabAccount.is_group=0
443 and tabAccount.docstatus!=2
444 and tabAccount.{key} LIKE %(txt)s
445 {condition} {match_condition}"""
Suraj Shettybfc195d2018-09-21 10:20:52 +0530446 .format(condition=condition, key=searchfield,
Nabin Hait3a15c922016-03-04 12:30:46 +0530447 match_condition=get_match_cond(doctype)), {
Neil Trini Lasrado30b97b02016-03-31 23:10:13 +0530448 'company': filters.get("company", ""),
Suraj Shetty4b404c42018-09-27 15:39:34 +0530449 'txt': '%' + txt + '%'
Maxwell Morais35572612016-07-21 23:42:59 -0300450 })
suyashphadtare049a88c2017-01-12 17:49:37 +0530451
452
453@frappe.whitelist()
454def warehouse_query(doctype, txt, searchfield, start, page_len, filters):
455 # Should be used when item code is passed in filters.
suyashphadtare750a0672017-01-18 15:35:01 +0530456 conditions, bin_conditions = [], []
457 filter_dict = get_doctype_wise_filters(filters)
458
459 sub_query = """ select round(`tabBin`.actual_qty, 2) from `tabBin`
suyashphadtare34ab1362017-01-31 15:14:44 +0530460 where `tabBin`.warehouse = `tabWarehouse`.name
461 {bin_conditions} """.format(
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530462 bin_conditions=get_filters_cond(doctype, filter_dict.get("Bin"),
Nabin Hait4e6ff8c2017-05-09 15:09:10 +0530463 bin_conditions, ignore_permissions=True))
suyashphadtare750a0672017-01-18 15:35:01 +0530464
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530465 query = """select `tabWarehouse`.name,
suyashphadtare34ab1362017-01-31 15:14:44 +0530466 CONCAT_WS(" : ", "Actual Qty", ifnull( ({sub_query}), 0) ) as actual_qty
467 from `tabWarehouse`
468 where
Suraj Shetty6ea3de92018-09-26 18:15:53 +0530469 `tabWarehouse`.`{key}` like {txt}
suyashphadtare34ab1362017-01-31 15:14:44 +0530470 {fcond} {mcond}
471 order by
472 `tabWarehouse`.name desc
473 limit
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530474 {start}, {page_len}
suyashphadtare34ab1362017-01-31 15:14:44 +0530475 """.format(
476 sub_query=sub_query,
Suraj Shettybfc195d2018-09-21 10:20:52 +0530477 key=searchfield,
suyashphadtare34ab1362017-01-31 15:14:44 +0530478 fcond=get_filters_cond(doctype, filter_dict.get("Warehouse"), conditions),
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530479 mcond=get_match_cond(doctype),
480 start=start,
481 page_len=page_len,
482 txt=frappe.db.escape('%{0}%'.format(txt))
483 )
484
485 return frappe.db.sql(query)
suyashphadtare750a0672017-01-18 15:35:01 +0530486
487
488def get_doctype_wise_filters(filters):
489 # Helper function to seperate filters doctype_wise
490 filter_dict = defaultdict(list)
491 for row in filters:
492 filter_dict[row[0]].append(row)
493 return filter_dict
tundebabzy2a4fefc2017-11-29 06:23:09 +0100494
495
496@frappe.whitelist()
497def get_batch_numbers(doctype, txt, searchfield, start, page_len, filters):
rohitwaghchaure9fbed562018-01-12 16:22:33 +0530498 query = """select batch_id from `tabBatch`
Doridel Cahanap59e4c322018-08-06 17:15:18 +0800499 where disabled = 0
500 and (expiry_date >= CURDATE() or expiry_date IS NULL)
Suraj Shettybfc195d2018-09-21 10:20:52 +0530501 and name like {txt}""".format(txt = frappe.db.escape('%{0}%'.format(txt)))
tundebabzy2a4fefc2017-11-29 06:23:09 +0100502
rohitwaghchaure9fbed562018-01-12 16:22:33 +0530503 if filters and filters.get('item'):
Suraj Shettybfc195d2018-09-21 10:20:52 +0530504 query += " and item = {item}".format(item = frappe.db.escape(filters.get('item')))
tundebabzy2a4fefc2017-11-29 06:23:09 +0100505
Sachin Mane64f48db2018-01-08 17:57:32 +0530506 return frappe.db.sql(query, filters)
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530507
Himanshud94a38e2020-05-18 14:26:26 +0530508
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530509@frappe.whitelist()
510def item_manufacturer_query(doctype, txt, searchfield, start, page_len, filters):
Maricabac4b932019-09-16 19:44:28 +0530511 item_filters = [
512 ['manufacturer', 'like', '%' + txt + '%'],
513 ['item_code', '=', filters.get("item_code")]
514 ]
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530515
Maricabac4b932019-09-16 19:44:28 +0530516 item_manufacturers = frappe.get_all(
517 "Item Manufacturer",
518 fields=["manufacturer", "manufacturer_part_no"],
519 filters=item_filters,
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530520 limit_start=start,
521 limit_page_length=page_len,
522 as_list=1
523 )
Maricabac4b932019-09-16 19:44:28 +0530524 return item_manufacturers
Saqibd9956092019-11-18 11:46:55 +0530525
Himanshud94a38e2020-05-18 14:26:26 +0530526
Saqibd9956092019-11-18 11:46:55 +0530527@frappe.whitelist()
528def get_purchase_receipts(doctype, txt, searchfield, start, page_len, filters):
529 query = """
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530530 select pr.name
Saqibd9956092019-11-18 11:46:55 +0530531 from `tabPurchase Receipt` pr, `tabPurchase Receipt Item` pritem
532 where pr.docstatus = 1 and pritem.parent = pr.name
533 and pr.name like {txt}""".format(txt = frappe.db.escape('%{0}%'.format(txt)))
534
535 if filters and filters.get('item_code'):
536 query += " and pritem.item_code = {item_code}".format(item_code = frappe.db.escape(filters.get('item_code')))
537
538 return frappe.db.sql(query, filters)
539
Himanshud94a38e2020-05-18 14:26:26 +0530540
Saqibd9956092019-11-18 11:46:55 +0530541@frappe.whitelist()
542def get_purchase_invoices(doctype, txt, searchfield, start, page_len, filters):
543 query = """
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530544 select pi.name
Saqibd9956092019-11-18 11:46:55 +0530545 from `tabPurchase Invoice` pi, `tabPurchase Invoice Item` piitem
546 where pi.docstatus = 1 and piitem.parent = pi.name
547 and pi.name like {txt}""".format(txt = frappe.db.escape('%{0}%'.format(txt)))
548
549 if filters and filters.get('item_code'):
550 query += " and piitem.item_code = {item_code}".format(item_code = frappe.db.escape(filters.get('item_code')))
551
552 return frappe.db.sql(query, filters)
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530553
Himanshud94a38e2020-05-18 14:26:26 +0530554
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530555@frappe.whitelist()
556def get_tax_template(doctype, txt, searchfield, start, page_len, filters):
557
558 item_doc = frappe.get_cached_doc('Item', filters.get('item_code'))
559 item_group = filters.get('item_group')
560 taxes = item_doc.taxes or []
561
562 while item_group:
563 item_group_doc = frappe.get_cached_doc('Item Group', item_group)
564 taxes += item_group_doc.taxes or []
565 item_group = item_group_doc.parent_item_group
566
567 if not taxes:
568 return frappe.db.sql(""" SELECT name FROM `tabItem Tax Template` """)
569 else:
570 args = {
571 'item_code': filters.get('item_code'),
572 'posting_date': filters.get('valid_from'),
mohammadahmad199041c0c9f2020-06-18 11:18:44 +0500573 'tax_category': filters.get('tax_category'),
574 'company': filters.get('company')
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530575 }
576
577 taxes = _get_item_tax_template(args, taxes, for_validate=True)
578 return [(d,) for d in set(taxes)]
Himanshud94a38e2020-05-18 14:26:26 +0530579
580
581def get_fields(doctype, fields=[]):
582 meta = frappe.get_meta(doctype)
583 fields.extend(meta.get_search_fields())
584
585 if meta.title_field and not meta.title_field.strip() in fields:
586 fields.insert(1, meta.title_field.strip())
587
588 return unique(fields)