blob: f373a43689ed76718f5b843ad683c83a92bad525 [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()
Saurabh02875592013-07-08 18:45:55 +053015def employee_query(doctype, txt, searchfield, start, page_len, filters):
Kanchan Chauhan7652b852016-11-16 15:29:01 +053016 conditions = []
Himanshud94a38e2020-05-18 14:26:26 +053017 fields = get_fields("Employee", ["name", "employee_name"])
18
19 return frappe.db.sql("""select {fields} from `tabEmployee`
Anand Doshibd67e872014-04-11 16:51:27 +053020 where status = 'Active'
21 and docstatus < 2
Anand Doshi48d3b542014-07-09 13:15:03 +053022 and ({key} like %(txt)s
23 or employee_name like %(txt)s)
Kanchan Chauhan7652b852016-11-16 15:29:01 +053024 {fcond} {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +053025 order by
Anand Doshi48d3b542014-07-09 13:15:03 +053026 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
27 if(locate(%(_txt)s, employee_name), locate(%(_txt)s, employee_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +053028 idx desc,
Anand Doshi652bc072014-04-16 15:21:46 +053029 name, employee_name
Anand Doshi48d3b542014-07-09 13:15:03 +053030 limit %(start)s, %(page_len)s""".format(**{
Himanshud94a38e2020-05-18 14:26:26 +053031 'fields': ", ".join(fields),
Anand Doshi48d3b542014-07-09 13:15:03 +053032 'key': searchfield,
Kanchan Chauhan7652b852016-11-16 15:29:01 +053033 'fcond': get_filters_cond(doctype, filters, conditions),
Anand Doshi48d3b542014-07-09 13:15:03 +053034 'mcond': get_match_cond(doctype)
35 }), {
36 'txt': "%%%s%%" % txt,
37 '_txt': txt.replace("%", ""),
38 'start': start,
39 'page_len': page_len
40 })
Saurabh02875592013-07-08 18:45:55 +053041
Himanshud94a38e2020-05-18 14:26:26 +053042
43# searches for leads which are not converted
Chinmay D. Paiaa121092020-07-01 21:14:32 +053044@frappe.whitelist()
Anand Doshibd67e872014-04-11 16:51:27 +053045def lead_query(doctype, txt, searchfield, start, page_len, filters):
Himanshud94a38e2020-05-18 14:26:26 +053046 fields = get_fields("Lead", ["name", "lead_name", "company_name"])
47
48 return frappe.db.sql("""select {fields} from `tabLead`
Anand Doshibd67e872014-04-11 16:51:27 +053049 where docstatus < 2
50 and ifnull(status, '') != 'Converted'
Anand Doshi48d3b542014-07-09 13:15:03 +053051 and ({key} like %(txt)s
52 or lead_name like %(txt)s
53 or company_name like %(txt)s)
54 {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +053055 order by
Anand Doshi48d3b542014-07-09 13:15:03 +053056 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
57 if(locate(%(_txt)s, lead_name), locate(%(_txt)s, lead_name), 99999),
58 if(locate(%(_txt)s, company_name), locate(%(_txt)s, company_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +053059 idx desc,
Anand Doshi652bc072014-04-16 15:21:46 +053060 name, lead_name
Anand Doshi48d3b542014-07-09 13:15:03 +053061 limit %(start)s, %(page_len)s""".format(**{
Himanshud94a38e2020-05-18 14:26:26 +053062 'fields': ", ".join(fields),
Anand Doshi48d3b542014-07-09 13:15:03 +053063 'key': searchfield,
64 'mcond':get_match_cond(doctype)
65 }), {
66 'txt': "%%%s%%" % txt,
67 '_txt': txt.replace("%", ""),
68 'start': start,
69 'page_len': page_len
70 })
Saurabh02875592013-07-08 18:45:55 +053071
Himanshud94a38e2020-05-18 14:26:26 +053072
Saurabh02875592013-07-08 18:45:55 +053073 # searches for customer
Chinmay D. Paiaa121092020-07-01 21:14:32 +053074@frappe.whitelist()
Saurabh02875592013-07-08 18:45:55 +053075def customer_query(doctype, txt, searchfield, start, page_len, filters):
KanchanChauhan4b888b92017-07-25 14:03:01 +053076 conditions = []
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053077 cust_master_name = frappe.defaults.get_user_default("cust_master_name")
Saurabhf52dc072013-07-10 13:07:49 +053078
Saurabh02875592013-07-08 18:45:55 +053079 if cust_master_name == "Customer Name":
80 fields = ["name", "customer_group", "territory"]
81 else:
82 fields = ["name", "customer_name", "customer_group", "territory"]
Rushabh Mehtab92087c2017-01-13 18:53:11 +053083
Himanshud94a38e2020-05-18 14:26:26 +053084 fields = get_fields("Customer", fields)
Saurabhf52dc072013-07-10 13:07:49 +053085
Himanshud94a38e2020-05-18 14:26:26 +053086 searchfields = frappe.get_meta("Customer").get_search_fields()
Console Admin86231662017-06-23 20:32:52 +030087 searchfields = " or ".join([field + " like %(txt)s" for field in searchfields])
Saurabh02875592013-07-08 18:45:55 +053088
Anand Doshi48d3b542014-07-09 13:15:03 +053089 return frappe.db.sql("""select {fields} from `tabCustomer`
Anand Doshibd67e872014-04-11 16:51:27 +053090 where docstatus < 2
Console Admin86231662017-06-23 20:32:52 +030091 and ({scond}) and disabled=0
KanchanChauhan4b888b92017-07-25 14:03:01 +053092 {fcond} {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +053093 order by
Anand Doshi48d3b542014-07-09 13:15:03 +053094 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
95 if(locate(%(_txt)s, customer_name), locate(%(_txt)s, customer_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +053096 idx desc,
Anand Doshibd67e872014-04-11 16:51:27 +053097 name, customer_name
Anand Doshi48d3b542014-07-09 13:15:03 +053098 limit %(start)s, %(page_len)s""".format(**{
Himanshud94a38e2020-05-18 14:26:26 +053099 "fields": ", ".join(fields),
Console Admin86231662017-06-23 20:32:52 +0300100 "scond": searchfields,
KanchanChauhan4b888b92017-07-25 14:03:01 +0530101 "mcond": get_match_cond(doctype),
102 "fcond": get_filters_cond(doctype, filters, conditions).replace('%', '%%'),
Anand Doshi48d3b542014-07-09 13:15:03 +0530103 }), {
104 'txt': "%%%s%%" % txt,
105 '_txt': txt.replace("%", ""),
106 'start': start,
107 'page_len': page_len
108 })
Saurabh02875592013-07-08 18:45:55 +0530109
Himanshud94a38e2020-05-18 14:26:26 +0530110
Saurabh02875592013-07-08 18:45:55 +0530111# searches for supplier
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530112@frappe.whitelist()
Saurabh02875592013-07-08 18:45:55 +0530113def supplier_query(doctype, txt, searchfield, start, page_len, filters):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530114 supp_master_name = frappe.defaults.get_user_default("supp_master_name")
Anand Doshibd67e872014-04-11 16:51:27 +0530115 if supp_master_name == "Supplier Name":
Zlash652e080982018-04-19 18:37:53 +0530116 fields = ["name", "supplier_group"]
Anand Doshibd67e872014-04-11 16:51:27 +0530117 else:
Zlash652e080982018-04-19 18:37:53 +0530118 fields = ["name", "supplier_name", "supplier_group"]
Himanshud94a38e2020-05-18 14:26:26 +0530119
120 fields = get_fields("Supplier", fields)
Saurabh02875592013-07-08 18:45:55 +0530121
Anand Doshi48d3b542014-07-09 13:15:03 +0530122 return frappe.db.sql("""select {field} from `tabSupplier`
Anand Doshibd67e872014-04-11 16:51:27 +0530123 where docstatus < 2
Anand Doshi48d3b542014-07-09 13:15:03 +0530124 and ({key} like %(txt)s
shreyas29b565f2016-01-25 17:30:49 +0530125 or supplier_name like %(txt)s) and disabled=0
Anand Doshi48d3b542014-07-09 13:15:03 +0530126 {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +0530127 order by
Anand Doshi48d3b542014-07-09 13:15:03 +0530128 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
129 if(locate(%(_txt)s, supplier_name), locate(%(_txt)s, supplier_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530130 idx desc,
Anand Doshibd67e872014-04-11 16:51:27 +0530131 name, supplier_name
Anand Doshi48d3b542014-07-09 13:15:03 +0530132 limit %(start)s, %(page_len)s """.format(**{
Himanshud94a38e2020-05-18 14:26:26 +0530133 'field': ', '.join(fields),
Anand Doshi48d3b542014-07-09 13:15:03 +0530134 'key': searchfield,
135 'mcond':get_match_cond(doctype)
136 }), {
137 'txt': "%%%s%%" % txt,
138 '_txt': txt.replace("%", ""),
139 'start': start,
140 'page_len': page_len
141 })
Anand Doshibd67e872014-04-11 16:51:27 +0530142
Himanshud94a38e2020-05-18 14:26:26 +0530143
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530144@frappe.whitelist()
Nabin Hait9a380ef2013-07-16 17:24:17 +0530145def tax_account_query(doctype, txt, searchfield, start, page_len, filters):
Deepesh Gargfbf6e562020-03-31 10:45:32 +0530146 company_currency = erpnext.get_company_currency(filters.get('company'))
147
Anand Doshibd67e872014-04-11 16:51:27 +0530148 tax_accounts = frappe.db.sql("""select name, parent_account from tabAccount
149 where tabAccount.docstatus!=2
Nabin Hait0c21e2a2014-03-21 11:14:49 +0530150 and account_type in (%s)
Rushabh Mehta38c6b522015-04-23 13:14:17 +0530151 and is_group = 0
Nabin Hait9a380ef2013-07-16 17:24:17 +0530152 and company = %s
Deepesh Gargfbf6e562020-03-31 10:45:32 +0530153 and account_currency = %s
Nabin Hait9a380ef2013-07-16 17:24:17 +0530154 and `%s` LIKE %s
Rushabh Mehta3574b372016-03-11 14:33:04 +0530155 order by idx desc, name
Anand Doshibd67e872014-04-11 16:51:27 +0530156 limit %s, %s""" %
Deepesh Gargfbf6e562020-03-31 10:45:32 +0530157 (", ".join(['%s']*len(filters.get("account_type"))), "%s", "%s", searchfield, "%s", "%s", "%s"),
158 tuple(filters.get("account_type") + [filters.get("company"), company_currency, "%%%s%%" % txt,
Nabin Hait0c21e2a2014-03-21 11:14:49 +0530159 start, page_len]))
160 if not tax_accounts:
Anand Doshibd67e872014-04-11 16:51:27 +0530161 tax_accounts = frappe.db.sql("""select name, parent_account from tabAccount
Rushabh Mehta38c6b522015-04-23 13:14:17 +0530162 where tabAccount.docstatus!=2 and is_group = 0
Deepesh Gargfbf6e562020-03-31 10:45:32 +0530163 and company = %s and account_currency = %s and `%s` LIKE %s limit %s, %s""" #nosec
164 % ("%s", "%s", searchfield, "%s", "%s", "%s"),
165 (filters.get("company"), company_currency, "%%%s%%" % txt, start, page_len))
Anand Doshibd67e872014-04-11 16:51:27 +0530166
Nabin Hait0c21e2a2014-03-21 11:14:49 +0530167 return tax_accounts
Saurabh02875592013-07-08 18:45:55 +0530168
Himanshud94a38e2020-05-18 14:26:26 +0530169
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530170@frappe.whitelist()
Rushabh Mehta203cc962016-04-07 15:25:43 +0530171def item_query(doctype, txt, searchfield, start, page_len, filters, as_dict=False):
Saurabh02875592013-07-08 18:45:55 +0530172 conditions = []
Saurabhf52dc072013-07-10 13:07:49 +0530173
marination3dbef9d2019-10-28 15:48:10 +0530174 #Get searchfields from meta and use in Item Link field query
marination1e754b12019-10-30 18:33:44 +0530175 meta = frappe.get_meta("Item", cached=True)
marination3dbef9d2019-10-28 15:48:10 +0530176 searchfields = meta.get_search_fields()
177
marination1e754b12019-10-30 18:33:44 +0530178 if "description" in searchfields:
179 searchfields.remove("description")
marination3dbef9d2019-10-28 15:48:10 +0530180
Rohit Waghchaurec42312e2019-11-19 19:05:23 +0530181 columns = ''
182 extra_searchfields = [field for field in searchfields
183 if not field in ["name", "item_group", "description"]]
184
185 if extra_searchfields:
186 columns = ", " + ", ".join(extra_searchfields)
marination1e754b12019-10-30 18:33:44 +0530187
188 searchfields = searchfields + [field for field in[searchfield or "name", "item_code", "item_group", "item_name"]
189 if not field in searchfields]
marination3dbef9d2019-10-28 15:48:10 +0530190 searchfields = " or ".join([field + " like %(txt)s" for field in searchfields])
191
Rushabh Mehtad5f9ebd2018-04-02 23:37:33 +0530192 description_cond = ''
193 if frappe.db.count('Item', cache=True) < 50000:
194 # scan description only if items are less than 50000
195 description_cond = 'or tabItem.description LIKE %(txt)s'
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
rohitwaghchaure79789072020-05-21 18:10:13 +0530207 and tabItem.has_variants=0
Rushabh Mehta864d1ea2014-06-23 12:20:12 +0530208 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 +0530209 and ({scond} or tabItem.item_code IN (select parent from `tabItem Barcode` where barcode LIKE %(txt)s)
Rohit Waghchaure2bfb0632019-03-02 21:47:55 +0530210 {description_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,
Nabin Haitc6285062016-03-30 13:10:25 +0530221 fcond=get_filters_cond(doctype, filters, conditions).replace('%', '%%'),
Rushabh Mehtad5f9ebd2018-04-02 23:37:33 +0530222 mcond=get_match_cond(doctype).replace('%', '%%'),
223 description_cond = description_cond),
Anand Doshi22c0d782013-11-04 16:23:04 +0530224 {
225 "today": nowdate(),
226 "txt": "%%%s%%" % txt,
Anand Doshi652bc072014-04-16 15:21:46 +0530227 "_txt": txt.replace("%", ""),
Anand Doshi22c0d782013-11-04 16:23:04 +0530228 "start": start,
229 "page_len": page_len
Rushabh Mehta203cc962016-04-07 15:25:43 +0530230 }, as_dict=as_dict)
Saurabh02875592013-07-08 18:45:55 +0530231
Himanshud94a38e2020-05-18 14:26:26 +0530232
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530233@frappe.whitelist()
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
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530260@frappe.whitelist()
Saurabh02875592013-07-08 18:45:55 +0530261def get_project_name(doctype, txt, searchfield, start, page_len, filters):
262 cond = ''
Nabin Haitf71011a2014-08-21 11:34:31 +0530263 if filters.get('customer'):
Suraj Shetty6ea3de92018-09-26 18:15:53 +0530264 cond = """(`tabProject`.customer = %s or
rohitwaghchauree3304722018-08-27 11:43:57 +0530265 ifnull(`tabProject`.customer,"")="") and""" %(frappe.db.escape(filters.get("customer")))
Anand Doshibd67e872014-04-11 16:51:27 +0530266
Himanshud94a38e2020-05-18 14:26:26 +0530267 fields = get_fields("Project", ["name"])
268
269 return frappe.db.sql("""select {fields} from `tabProject`
Anand Doshibd67e872014-04-11 16:51:27 +0530270 where `tabProject`.status not in ("Completed", "Cancelled")
Rushabh Mehta3574b372016-03-11 14:33:04 +0530271 and {cond} `tabProject`.name like %(txt)s {match_cond}
272 order by
273 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
274 idx desc,
275 `tabProject`.name asc
276 limit {start}, {page_len}""".format(
Himanshud94a38e2020-05-18 14:26:26 +0530277 fields=", ".join(['`tabProject`.{0}'.format(f) for f in fields]),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530278 cond=cond,
279 match_cond=get_match_cond(doctype),
280 start=start,
281 page_len=page_len), {
282 "txt": "%{0}%".format(txt),
Nabin Haitdf4deba2016-03-16 11:16:31 +0530283 "_txt": txt.replace('%', '')
Rushabh Mehta3574b372016-03-11 14:33:04 +0530284 })
Anand Doshibd67e872014-04-11 16:51:27 +0530285
tundebabzyf6d738b2017-09-18 12:40:09 +0100286
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530287@frappe.whitelist()
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530288def get_delivery_notes_to_be_billed(doctype, txt, searchfield, start, page_len, filters, as_dict):
Himanshud94a38e2020-05-18 14:26:26 +0530289 fields = get_fields("Delivery Note", ["name", "customer", "posting_date"])
290
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530291 return frappe.db.sql("""
Himanshud94a38e2020-05-18 14:26:26 +0530292 select %(fields)s
Anand Doshibd67e872014-04-11 16:51:27 +0530293 from `tabDelivery Note`
294 where `tabDelivery Note`.`%(key)s` like %(txt)s and
tundebabzyf6d738b2017-09-18 12:40:09 +0100295 `tabDelivery Note`.docstatus = 1
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530296 and status not in ("Stopped", "Closed") %(fcond)s
tundebabzyf6d738b2017-09-18 12:40:09 +0100297 and (
298 (`tabDelivery Note`.is_return = 0 and `tabDelivery Note`.per_billed < 100)
299 or `tabDelivery Note`.grand_total = 0
300 or (
301 `tabDelivery Note`.is_return = 1
302 and return_against in (select name from `tabDelivery Note` where per_billed < 100)
303 )
304 )
rohitwaghchaured07a3e12019-05-15 07:46:28 +0530305 %(mcond)s order by `tabDelivery Note`.`%(key)s` asc limit %(start)s, %(page_len)s
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530306 """ % {
Himanshud94a38e2020-05-18 14:26:26 +0530307 "fields": ", ".join(["`tabDelivery Note`.{0}".format(f) for f in fields]),
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530308 "key": searchfield,
309 "fcond": get_filters_cond(doctype, filters, []),
310 "mcond": get_match_cond(doctype),
rohitwaghchaured07a3e12019-05-15 07:46:28 +0530311 "start": start,
312 "page_len": page_len,
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530313 "txt": "%(txt)s"
tundebabzyf6d738b2017-09-18 12:40:09 +0100314 }, {"txt": ("%%%s%%" % txt)}, as_dict=as_dict)
315
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530316
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530317@frappe.whitelist()
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530318def get_batch_no(doctype, txt, searchfield, start, page_len, filters):
Neil Trini Lasradoebb60f52015-07-08 14:36:09 +0530319 cond = ""
320 if filters.get("posting_date"):
Nabin Hait7918b922018-01-31 15:30:03 +0530321 cond = "and (batch.expiry_date is null or batch.expiry_date >= %(posting_date)s)"
Rushabh Mehtab6398be2015-08-26 10:50:16 +0530322
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530323 batch_nos = None
324 args = {
325 'item_code': filters.get("item_code"),
326 'warehouse': filters.get("warehouse"),
327 'posting_date': filters.get('posting_date'),
Anand Doshi0dc79f42015-04-06 12:59:34 +0530328 'txt': "%{0}%".format(txt),
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530329 "start": start,
330 "page_len": page_len
331 }
332
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530333 having_clause = "having sum(sle.actual_qty) > 0"
334 if filters.get("is_return"):
335 having_clause = ""
336
Anand Doshi0dc79f42015-04-06 12:59:34 +0530337 if args.get('warehouse'):
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530338 batch_nos = frappe.db.sql("""select sle.batch_no, round(sum(sle.actual_qty),2), sle.stock_uom,
339 concat('MFG-',batch.manufacturing_date), concat('EXP-',batch.expiry_date)
340 from `tabStock Ledger Entry` sle
341 INNER JOIN `tabBatch` batch on sle.batch_no = batch.name
342 where
343 batch.disabled = 0
344 and sle.item_code = %(item_code)s
345 and sle.warehouse = %(warehouse)s
346 and (sle.batch_no like %(txt)s
Sun Howwrongbum088be372019-12-24 12:29:25 +0530347 or batch.expiry_date like %(txt)s
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530348 or batch.manufacturing_date like %(txt)s)
349 and batch.docstatus < 2
350 {cond}
351 {match_conditions}
352 group by batch_no {having_clause}
353 order by batch.expiry_date, sle.batch_no desc
354 limit %(start)s, %(page_len)s""".format(
355 cond=cond,
356 match_conditions=get_match_cond(doctype),
357 having_clause = having_clause
358 ), args)
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530359
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530360 return batch_nos
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530361 else:
sivankar621740e2018-02-12 14:33:40 +0530362 return frappe.db.sql("""select name, concat('MFG-', manufacturing_date), concat('EXP-',expiry_date) from `tabBatch` batch
Doridel Cahanap59e4c322018-08-06 17:15:18 +0800363 where batch.disabled = 0
364 and item = %(item_code)s
sivankar621740e2018-02-12 14:33:40 +0530365 and (name like %(txt)s
Sun Howwrongbum088be372019-12-24 12:29:25 +0530366 or expiry_date like %(txt)s
sivankar621740e2018-02-12 14:33:40 +0530367 or manufacturing_date like %(txt)s)
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530368 and docstatus < 2
Neil Trini Lasradoebb60f52015-07-08 14:36:09 +0530369 {0}
Anand Doshi0dc79f42015-04-06 12:59:34 +0530370 {match_conditions}
371 order by expiry_date, name desc
Nabin Haite52ee552015-09-02 10:55:32 +0530372 limit %(start)s, %(page_len)s""".format(cond, match_conditions=get_match_cond(doctype)), args)
Nabin Haitea4aa042014-05-28 12:56:28 +0530373
Himanshud94a38e2020-05-18 14:26:26 +0530374
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530375@frappe.whitelist()
Nabin Haitea4aa042014-05-28 12:56:28 +0530376def get_account_list(doctype, txt, searchfield, start, page_len, filters):
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530377 filter_list = []
Nabin Haitea4aa042014-05-28 12:56:28 +0530378
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530379 if isinstance(filters, dict):
380 for key, val in filters.items():
381 if isinstance(val, (list, tuple)):
382 filter_list.append([doctype, key, val[0], val[1]])
383 else:
384 filter_list.append([doctype, key, "=", val])
bhupeshg2e2e973f2015-04-14 22:15:24 +0530385 elif isinstance(filters, list):
386 filter_list.extend(filters)
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530387
Rushabh Mehta38c6b522015-04-23 13:14:17 +0530388 if "is_group" not in [d[1] for d in filter_list]:
389 filter_list.append(["Account", "is_group", "=", "0"])
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530390
391 if searchfield and txt:
392 filter_list.append([doctype, searchfield, "like", "%%%s%%" % txt])
393
Rushabh Mehtac0bb4532014-09-09 16:15:35 +0530394 return frappe.desk.reportview.execute("Account", filters = filter_list,
Nabin Haitea4aa042014-05-28 12:56:28 +0530395 fields = ["name", "parent_account"],
396 limit_start=start, limit_page_length=page_len, as_list=True)
Anand Doshifaefeaa2014-06-24 18:53:04 +0530397
Himanshud94a38e2020-05-18 14:26:26 +0530398
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530399@frappe.whitelist()
Marica299e2172020-04-28 13:00:04 +0530400def get_blanket_orders(doctype, txt, searchfield, start, page_len, filters):
401 return frappe.db.sql("""select distinct bo.name, bo.blanket_order_type, bo.to_date
402 from `tabBlanket Order` bo, `tabBlanket Order Item` boi
403 where
404 boi.parent = bo.name
405 and boi.item_code = {item_code}
406 and bo.blanket_order_type = '{blanket_order_type}'
407 and bo.company = {company}
408 and bo.docstatus = 1"""
409 .format(item_code = frappe.db.escape(filters.get("item")),
410 blanket_order_type = filters.get("blanket_order_type"),
411 company = frappe.db.escape(filters.get("company"))
412 ))
Nabin Haitafd14f62015-10-19 11:55:28 +0530413
Himanshud94a38e2020-05-18 14:26:26 +0530414
Nabin Haitafd14f62015-10-19 11:55:28 +0530415@frappe.whitelist()
416def get_income_account(doctype, txt, searchfield, start, page_len, filters):
417 from erpnext.controllers.queries import get_match_cond
418
419 # income account can be any Credit account,
420 # but can also be a Asset account with account_type='Income Account' in special circumstances.
421 # Hence the first condition is an "OR"
422 if not filters: filters = {}
423
Anand Doshi21e09a22015-10-29 12:21:41 +0530424 condition = ""
Nabin Haitafd14f62015-10-19 11:55:28 +0530425 if filters.get("company"):
426 condition += "and tabAccount.company = %(company)s"
Anand Doshi21e09a22015-10-29 12:21:41 +0530427
Nabin Haitafd14f62015-10-19 11:55:28 +0530428 return frappe.db.sql("""select tabAccount.name from `tabAccount`
429 where (tabAccount.report_type = "Profit and Loss"
430 or tabAccount.account_type in ("Income Account", "Temporary"))
431 and tabAccount.is_group=0
432 and tabAccount.`{key}` LIKE %(txt)s
Rushabh Mehta3574b372016-03-11 14:33:04 +0530433 {condition} {match_condition}
434 order by idx desc, name"""
Nabin Haitafd14f62015-10-19 11:55:28 +0530435 .format(condition=condition, match_condition=get_match_cond(doctype), key=searchfield), {
Suraj Shetty4b404c42018-09-27 15:39:34 +0530436 'txt': '%' + txt + '%',
Nabin Haitafd14f62015-10-19 11:55:28 +0530437 'company': filters.get("company", "")
Anand Doshi21e09a22015-10-29 12:21:41 +0530438 })
Nabin Hait3a15c922016-03-04 12:30:46 +0530439
440
441@frappe.whitelist()
442def get_expense_account(doctype, txt, searchfield, start, page_len, filters):
443 from erpnext.controllers.queries import get_match_cond
Rushabh Mehta203cc962016-04-07 15:25:43 +0530444
Nabin Hait3a15c922016-03-04 12:30:46 +0530445 if not filters: filters = {}
446
447 condition = ""
448 if filters.get("company"):
449 condition += "and tabAccount.company = %(company)s"
Rushabh Mehta203cc962016-04-07 15:25:43 +0530450
Nabin Hait3a15c922016-03-04 12:30:46 +0530451 return frappe.db.sql("""select tabAccount.name from `tabAccount`
452 where (tabAccount.report_type = "Profit and Loss"
Mangesh-Khairnar5619db22019-08-21 14:49:24 +0530453 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 +0530454 and tabAccount.is_group=0
455 and tabAccount.docstatus!=2
456 and tabAccount.{key} LIKE %(txt)s
457 {condition} {match_condition}"""
Suraj Shettybfc195d2018-09-21 10:20:52 +0530458 .format(condition=condition, key=searchfield,
Nabin Hait3a15c922016-03-04 12:30:46 +0530459 match_condition=get_match_cond(doctype)), {
Neil Trini Lasrado30b97b02016-03-31 23:10:13 +0530460 'company': filters.get("company", ""),
Suraj Shetty4b404c42018-09-27 15:39:34 +0530461 'txt': '%' + txt + '%'
Maxwell Morais35572612016-07-21 23:42:59 -0300462 })
suyashphadtare049a88c2017-01-12 17:49:37 +0530463
464
465@frappe.whitelist()
466def warehouse_query(doctype, txt, searchfield, start, page_len, filters):
467 # Should be used when item code is passed in filters.
suyashphadtare750a0672017-01-18 15:35:01 +0530468 conditions, bin_conditions = [], []
469 filter_dict = get_doctype_wise_filters(filters)
470
471 sub_query = """ select round(`tabBin`.actual_qty, 2) from `tabBin`
suyashphadtare34ab1362017-01-31 15:14:44 +0530472 where `tabBin`.warehouse = `tabWarehouse`.name
473 {bin_conditions} """.format(
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530474 bin_conditions=get_filters_cond(doctype, filter_dict.get("Bin"),
Nabin Hait4e6ff8c2017-05-09 15:09:10 +0530475 bin_conditions, ignore_permissions=True))
suyashphadtare750a0672017-01-18 15:35:01 +0530476
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530477 query = """select `tabWarehouse`.name,
suyashphadtare34ab1362017-01-31 15:14:44 +0530478 CONCAT_WS(" : ", "Actual Qty", ifnull( ({sub_query}), 0) ) as actual_qty
479 from `tabWarehouse`
480 where
Suraj Shetty6ea3de92018-09-26 18:15:53 +0530481 `tabWarehouse`.`{key}` like {txt}
suyashphadtare34ab1362017-01-31 15:14:44 +0530482 {fcond} {mcond}
483 order by
484 `tabWarehouse`.name desc
485 limit
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530486 {start}, {page_len}
suyashphadtare34ab1362017-01-31 15:14:44 +0530487 """.format(
488 sub_query=sub_query,
Suraj Shettybfc195d2018-09-21 10:20:52 +0530489 key=searchfield,
suyashphadtare34ab1362017-01-31 15:14:44 +0530490 fcond=get_filters_cond(doctype, filter_dict.get("Warehouse"), conditions),
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530491 mcond=get_match_cond(doctype),
492 start=start,
493 page_len=page_len,
494 txt=frappe.db.escape('%{0}%'.format(txt))
495 )
496
497 return frappe.db.sql(query)
suyashphadtare750a0672017-01-18 15:35:01 +0530498
499
500def get_doctype_wise_filters(filters):
501 # Helper function to seperate filters doctype_wise
502 filter_dict = defaultdict(list)
503 for row in filters:
504 filter_dict[row[0]].append(row)
505 return filter_dict
tundebabzy2a4fefc2017-11-29 06:23:09 +0100506
507
508@frappe.whitelist()
509def get_batch_numbers(doctype, txt, searchfield, start, page_len, filters):
rohitwaghchaure9fbed562018-01-12 16:22:33 +0530510 query = """select batch_id from `tabBatch`
Doridel Cahanap59e4c322018-08-06 17:15:18 +0800511 where disabled = 0
512 and (expiry_date >= CURDATE() or expiry_date IS NULL)
Suraj Shettybfc195d2018-09-21 10:20:52 +0530513 and name like {txt}""".format(txt = frappe.db.escape('%{0}%'.format(txt)))
tundebabzy2a4fefc2017-11-29 06:23:09 +0100514
rohitwaghchaure9fbed562018-01-12 16:22:33 +0530515 if filters and filters.get('item'):
Suraj Shettybfc195d2018-09-21 10:20:52 +0530516 query += " and item = {item}".format(item = frappe.db.escape(filters.get('item')))
tundebabzy2a4fefc2017-11-29 06:23:09 +0100517
Sachin Mane64f48db2018-01-08 17:57:32 +0530518 return frappe.db.sql(query, filters)
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530519
Himanshud94a38e2020-05-18 14:26:26 +0530520
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530521@frappe.whitelist()
522def item_manufacturer_query(doctype, txt, searchfield, start, page_len, filters):
Maricabac4b932019-09-16 19:44:28 +0530523 item_filters = [
524 ['manufacturer', 'like', '%' + txt + '%'],
525 ['item_code', '=', filters.get("item_code")]
526 ]
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530527
Maricabac4b932019-09-16 19:44:28 +0530528 item_manufacturers = frappe.get_all(
529 "Item Manufacturer",
530 fields=["manufacturer", "manufacturer_part_no"],
531 filters=item_filters,
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530532 limit_start=start,
533 limit_page_length=page_len,
534 as_list=1
535 )
Maricabac4b932019-09-16 19:44:28 +0530536 return item_manufacturers
Saqibd9956092019-11-18 11:46:55 +0530537
Himanshud94a38e2020-05-18 14:26:26 +0530538
Saqibd9956092019-11-18 11:46:55 +0530539@frappe.whitelist()
540def get_purchase_receipts(doctype, txt, searchfield, start, page_len, filters):
541 query = """
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530542 select pr.name
Saqibd9956092019-11-18 11:46:55 +0530543 from `tabPurchase Receipt` pr, `tabPurchase Receipt Item` pritem
544 where pr.docstatus = 1 and pritem.parent = pr.name
545 and pr.name like {txt}""".format(txt = frappe.db.escape('%{0}%'.format(txt)))
546
547 if filters and filters.get('item_code'):
548 query += " and pritem.item_code = {item_code}".format(item_code = frappe.db.escape(filters.get('item_code')))
549
550 return frappe.db.sql(query, filters)
551
Himanshud94a38e2020-05-18 14:26:26 +0530552
Saqibd9956092019-11-18 11:46:55 +0530553@frappe.whitelist()
554def get_purchase_invoices(doctype, txt, searchfield, start, page_len, filters):
555 query = """
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530556 select pi.name
Saqibd9956092019-11-18 11:46:55 +0530557 from `tabPurchase Invoice` pi, `tabPurchase Invoice Item` piitem
558 where pi.docstatus = 1 and piitem.parent = pi.name
559 and pi.name like {txt}""".format(txt = frappe.db.escape('%{0}%'.format(txt)))
560
561 if filters and filters.get('item_code'):
562 query += " and piitem.item_code = {item_code}".format(item_code = frappe.db.escape(filters.get('item_code')))
563
564 return frappe.db.sql(query, filters)
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530565
Himanshud94a38e2020-05-18 14:26:26 +0530566
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530567@frappe.whitelist()
568def get_tax_template(doctype, txt, searchfield, start, page_len, filters):
569
570 item_doc = frappe.get_cached_doc('Item', filters.get('item_code'))
571 item_group = filters.get('item_group')
572 taxes = item_doc.taxes or []
573
574 while item_group:
575 item_group_doc = frappe.get_cached_doc('Item Group', item_group)
576 taxes += item_group_doc.taxes or []
577 item_group = item_group_doc.parent_item_group
578
579 if not taxes:
580 return frappe.db.sql(""" SELECT name FROM `tabItem Tax Template` """)
581 else:
582 args = {
583 'item_code': filters.get('item_code'),
584 'posting_date': filters.get('valid_from'),
585 'tax_category': filters.get('tax_category')
586 }
587
588 taxes = _get_item_tax_template(args, taxes, for_validate=True)
589 return [(d,) for d in set(taxes)]
Himanshud94a38e2020-05-18 14:26:26 +0530590
591
592def get_fields(doctype, fields=[]):
593 meta = frappe.get_meta(doctype)
594 fields.extend(meta.get_search_fields())
595
596 if meta.title_field and not meta.title_field.strip() in fields:
597 fields.insert(1, meta.title_field.strip())
598
599 return unique(fields)