blob: 5febfd6bf28d93bc3e8ecd5cb9d5dd84932fba8e [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
Saurabh02875592013-07-08 18:45:55 +053011
Saurabh02875592013-07-08 18:45:55 +053012 # searches for active employees
13def employee_query(doctype, txt, searchfield, start, page_len, filters):
Kanchan Chauhan7652b852016-11-16 15:29:01 +053014 conditions = []
Anand Doshibd67e872014-04-11 16:51:27 +053015 return frappe.db.sql("""select name, employee_name from `tabEmployee`
16 where status = 'Active'
17 and docstatus < 2
Anand Doshi48d3b542014-07-09 13:15:03 +053018 and ({key} like %(txt)s
19 or employee_name like %(txt)s)
Kanchan Chauhan7652b852016-11-16 15:29:01 +053020 {fcond} {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +053021 order by
Anand Doshi48d3b542014-07-09 13:15:03 +053022 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
23 if(locate(%(_txt)s, employee_name), locate(%(_txt)s, employee_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +053024 idx desc,
Anand Doshi652bc072014-04-16 15:21:46 +053025 name, employee_name
Anand Doshi48d3b542014-07-09 13:15:03 +053026 limit %(start)s, %(page_len)s""".format(**{
27 'key': searchfield,
Kanchan Chauhan7652b852016-11-16 15:29:01 +053028 'fcond': get_filters_cond(doctype, filters, conditions),
Anand Doshi48d3b542014-07-09 13:15:03 +053029 'mcond': get_match_cond(doctype)
30 }), {
31 'txt': "%%%s%%" % txt,
32 '_txt': txt.replace("%", ""),
33 'start': start,
34 'page_len': page_len
35 })
Saurabh02875592013-07-08 18:45:55 +053036
37 # searches for leads which are not converted
Anand Doshibd67e872014-04-11 16:51:27 +053038def lead_query(doctype, txt, searchfield, start, page_len, filters):
Anand Doshie9baaa62014-02-26 12:35:33 +053039 return frappe.db.sql("""select name, lead_name, company_name from `tabLead`
Anand Doshibd67e872014-04-11 16:51:27 +053040 where docstatus < 2
41 and ifnull(status, '') != 'Converted'
Anand Doshi48d3b542014-07-09 13:15:03 +053042 and ({key} like %(txt)s
43 or lead_name like %(txt)s
44 or company_name like %(txt)s)
45 {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +053046 order by
Anand Doshi48d3b542014-07-09 13:15:03 +053047 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
48 if(locate(%(_txt)s, lead_name), locate(%(_txt)s, lead_name), 99999),
49 if(locate(%(_txt)s, company_name), locate(%(_txt)s, company_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +053050 idx desc,
Anand Doshi652bc072014-04-16 15:21:46 +053051 name, lead_name
Anand Doshi48d3b542014-07-09 13:15:03 +053052 limit %(start)s, %(page_len)s""".format(**{
53 'key': searchfield,
54 'mcond':get_match_cond(doctype)
55 }), {
56 'txt': "%%%s%%" % txt,
57 '_txt': txt.replace("%", ""),
58 'start': start,
59 'page_len': page_len
60 })
Saurabh02875592013-07-08 18:45:55 +053061
62 # searches for customer
63def customer_query(doctype, txt, searchfield, start, page_len, filters):
KanchanChauhan4b888b92017-07-25 14:03:01 +053064 conditions = []
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053065 cust_master_name = frappe.defaults.get_user_default("cust_master_name")
Saurabhf52dc072013-07-10 13:07:49 +053066
Saurabh02875592013-07-08 18:45:55 +053067 if cust_master_name == "Customer Name":
68 fields = ["name", "customer_group", "territory"]
69 else:
70 fields = ["name", "customer_name", "customer_group", "territory"]
Rushabh Mehtab92087c2017-01-13 18:53:11 +053071
Maxwell Morais35572612016-07-21 23:42:59 -030072 meta = frappe.get_meta("Customer")
Console Admin86231662017-06-23 20:32:52 +030073 searchfields = meta.get_search_fields()
74 searchfields = searchfields + [f for f in [searchfield or "name", "customer_name"] \
75 if not f in searchfields]
76 fields = fields + [f for f in searchfields if not f in fields]
Saurabhf52dc072013-07-10 13:07:49 +053077
Anand Doshibd67e872014-04-11 16:51:27 +053078 fields = ", ".join(fields)
Console Admin86231662017-06-23 20:32:52 +030079 searchfields = " or ".join([field + " like %(txt)s" for field in searchfields])
Saurabh02875592013-07-08 18:45:55 +053080
Anand Doshi48d3b542014-07-09 13:15:03 +053081 return frappe.db.sql("""select {fields} from `tabCustomer`
Anand Doshibd67e872014-04-11 16:51:27 +053082 where docstatus < 2
Console Admin86231662017-06-23 20:32:52 +030083 and ({scond}) and disabled=0
KanchanChauhan4b888b92017-07-25 14:03:01 +053084 {fcond} {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +053085 order by
Anand Doshi48d3b542014-07-09 13:15:03 +053086 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
87 if(locate(%(_txt)s, customer_name), locate(%(_txt)s, customer_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +053088 idx desc,
Anand Doshibd67e872014-04-11 16:51:27 +053089 name, customer_name
Anand Doshi48d3b542014-07-09 13:15:03 +053090 limit %(start)s, %(page_len)s""".format(**{
91 "fields": fields,
Console Admin86231662017-06-23 20:32:52 +030092 "scond": searchfields,
KanchanChauhan4b888b92017-07-25 14:03:01 +053093 "mcond": get_match_cond(doctype),
94 "fcond": get_filters_cond(doctype, filters, conditions).replace('%', '%%'),
Anand Doshi48d3b542014-07-09 13:15:03 +053095 }), {
96 'txt': "%%%s%%" % txt,
97 '_txt': txt.replace("%", ""),
98 'start': start,
99 'page_len': page_len
100 })
Saurabh02875592013-07-08 18:45:55 +0530101
102# searches for supplier
103def supplier_query(doctype, txt, searchfield, start, page_len, filters):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530104 supp_master_name = frappe.defaults.get_user_default("supp_master_name")
Anand Doshibd67e872014-04-11 16:51:27 +0530105 if supp_master_name == "Supplier Name":
Zlash652e080982018-04-19 18:37:53 +0530106 fields = ["name", "supplier_group"]
Anand Doshibd67e872014-04-11 16:51:27 +0530107 else:
Zlash652e080982018-04-19 18:37:53 +0530108 fields = ["name", "supplier_name", "supplier_group"]
Anand Doshibd67e872014-04-11 16:51:27 +0530109 fields = ", ".join(fields)
Saurabh02875592013-07-08 18:45:55 +0530110
Anand Doshi48d3b542014-07-09 13:15:03 +0530111 return frappe.db.sql("""select {field} from `tabSupplier`
Anand Doshibd67e872014-04-11 16:51:27 +0530112 where docstatus < 2
Anand Doshi48d3b542014-07-09 13:15:03 +0530113 and ({key} like %(txt)s
shreyas29b565f2016-01-25 17:30:49 +0530114 or supplier_name like %(txt)s) and disabled=0
Anand Doshi48d3b542014-07-09 13:15:03 +0530115 {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +0530116 order by
Anand Doshi48d3b542014-07-09 13:15:03 +0530117 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
118 if(locate(%(_txt)s, supplier_name), locate(%(_txt)s, supplier_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530119 idx desc,
Anand Doshibd67e872014-04-11 16:51:27 +0530120 name, supplier_name
Anand Doshi48d3b542014-07-09 13:15:03 +0530121 limit %(start)s, %(page_len)s """.format(**{
122 'field': fields,
123 'key': searchfield,
124 'mcond':get_match_cond(doctype)
125 }), {
126 'txt': "%%%s%%" % txt,
127 '_txt': txt.replace("%", ""),
128 'start': start,
129 'page_len': page_len
130 })
Anand Doshibd67e872014-04-11 16:51:27 +0530131
Nabin Hait9a380ef2013-07-16 17:24:17 +0530132def tax_account_query(doctype, txt, searchfield, start, page_len, filters):
Deepesh Gargfbf6e562020-03-31 10:45:32 +0530133 company_currency = erpnext.get_company_currency(filters.get('company'))
134
Anand Doshibd67e872014-04-11 16:51:27 +0530135 tax_accounts = frappe.db.sql("""select name, parent_account from tabAccount
136 where tabAccount.docstatus!=2
Nabin Hait0c21e2a2014-03-21 11:14:49 +0530137 and account_type in (%s)
Rushabh Mehta38c6b522015-04-23 13:14:17 +0530138 and is_group = 0
Nabin Hait9a380ef2013-07-16 17:24:17 +0530139 and company = %s
Deepesh Gargfbf6e562020-03-31 10:45:32 +0530140 and account_currency = %s
Nabin Hait9a380ef2013-07-16 17:24:17 +0530141 and `%s` LIKE %s
Rushabh Mehta3574b372016-03-11 14:33:04 +0530142 order by idx desc, name
Anand Doshibd67e872014-04-11 16:51:27 +0530143 limit %s, %s""" %
Deepesh Gargfbf6e562020-03-31 10:45:32 +0530144 (", ".join(['%s']*len(filters.get("account_type"))), "%s", "%s", searchfield, "%s", "%s", "%s"),
145 tuple(filters.get("account_type") + [filters.get("company"), company_currency, "%%%s%%" % txt,
Nabin Hait0c21e2a2014-03-21 11:14:49 +0530146 start, page_len]))
147 if not tax_accounts:
Anand Doshibd67e872014-04-11 16:51:27 +0530148 tax_accounts = frappe.db.sql("""select name, parent_account from tabAccount
Rushabh Mehta38c6b522015-04-23 13:14:17 +0530149 where tabAccount.docstatus!=2 and is_group = 0
Deepesh Gargfbf6e562020-03-31 10:45:32 +0530150 and company = %s and account_currency = %s and `%s` LIKE %s limit %s, %s""" #nosec
151 % ("%s", "%s", searchfield, "%s", "%s", "%s"),
152 (filters.get("company"), company_currency, "%%%s%%" % txt, start, page_len))
Anand Doshibd67e872014-04-11 16:51:27 +0530153
Nabin Hait0c21e2a2014-03-21 11:14:49 +0530154 return tax_accounts
Saurabh02875592013-07-08 18:45:55 +0530155
Rushabh Mehta203cc962016-04-07 15:25:43 +0530156def item_query(doctype, txt, searchfield, start, page_len, filters, as_dict=False):
Saurabh02875592013-07-08 18:45:55 +0530157 conditions = []
Saurabhf52dc072013-07-10 13:07:49 +0530158
marination3dbef9d2019-10-28 15:48:10 +0530159 #Get searchfields from meta and use in Item Link field query
marination1e754b12019-10-30 18:33:44 +0530160 meta = frappe.get_meta("Item", cached=True)
marination3dbef9d2019-10-28 15:48:10 +0530161 searchfields = meta.get_search_fields()
162
marination1e754b12019-10-30 18:33:44 +0530163 if "description" in searchfields:
164 searchfields.remove("description")
marination3dbef9d2019-10-28 15:48:10 +0530165
Rohit Waghchaurec42312e2019-11-19 19:05:23 +0530166 columns = ''
167 extra_searchfields = [field for field in searchfields
168 if not field in ["name", "item_group", "description"]]
169
170 if extra_searchfields:
171 columns = ", " + ", ".join(extra_searchfields)
marination1e754b12019-10-30 18:33:44 +0530172
173 searchfields = searchfields + [field for field in[searchfield or "name", "item_code", "item_group", "item_name"]
174 if not field in searchfields]
marination3dbef9d2019-10-28 15:48:10 +0530175 searchfields = " or ".join([field + " like %(txt)s" for field in searchfields])
176
Rushabh Mehtad5f9ebd2018-04-02 23:37:33 +0530177 description_cond = ''
178 if frappe.db.count('Item', cache=True) < 50000:
179 # scan description only if items are less than 50000
180 description_cond = 'or tabItem.description LIKE %(txt)s'
181
rohitwaghchaure05ac7212020-04-06 10:17:57 +0530182 extra_cond = " and tabItem.has_variants=0"
183 if (filters and isinstance(filters, dict)
184 and filters.get("doctype") == "BOM"):
185 extra_cond = ""
186 del filters["doctype"]
187
Prateeksha Singh984a7a72018-05-17 17:29:36 +0530188 return frappe.db.sql("""select tabItem.name,
Anand Doshibd67e872014-04-11 16:51:27 +0530189 if(length(tabItem.item_name) > 40,
190 concat(substr(tabItem.item_name, 1, 40), "..."), item_name) as item_name,
Prateeksha Singh984a7a72018-05-17 17:29:36 +0530191 tabItem.item_group,
Saurabh02875592013-07-08 18:45:55 +0530192 if(length(tabItem.description) > 40, \
Rohit Waghchaurec42312e2019-11-19 19:05:23 +0530193 concat(substr(tabItem.description, 1, 40), "..."), description) as description
marination1e754b12019-10-30 18:33:44 +0530194 {columns}
Anand Doshibd67e872014-04-11 16:51:27 +0530195 from tabItem
Anand Doshi22c0d782013-11-04 16:23:04 +0530196 where tabItem.docstatus < 2
Anand Doshi21e09a22015-10-29 12:21:41 +0530197 and tabItem.disabled=0
Rushabh Mehta864d1ea2014-06-23 12:20:12 +0530198 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 +0530199 and ({scond} or tabItem.item_code IN (select parent from `tabItem Barcode` where barcode LIKE %(txt)s)
Rohit Waghchaure2bfb0632019-03-02 21:47:55 +0530200 {description_cond})
rohitwaghchaure05ac7212020-04-06 10:17:57 +0530201 {extra_cond}
Anand Doshi22c0d782013-11-04 16:23:04 +0530202 {fcond} {mcond}
Anand Doshi652bc072014-04-16 15:21:46 +0530203 order by
204 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
205 if(locate(%(_txt)s, item_name), locate(%(_txt)s, item_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530206 idx desc,
Anand Doshi652bc072014-04-16 15:21:46 +0530207 name, item_name
Rushabh Mehtabc4e2cd2017-10-17 12:30:34 +0530208 limit %(start)s, %(page_len)s """.format(
209 key=searchfield,
marination1e754b12019-10-30 18:33:44 +0530210 columns=columns,
marination3dbef9d2019-10-28 15:48:10 +0530211 scond=searchfields,
rohitwaghchaure05ac7212020-04-06 10:17:57 +0530212 extra_cond=extra_cond,
Nabin Haitc6285062016-03-30 13:10:25 +0530213 fcond=get_filters_cond(doctype, filters, conditions).replace('%', '%%'),
Rushabh Mehtad5f9ebd2018-04-02 23:37:33 +0530214 mcond=get_match_cond(doctype).replace('%', '%%'),
215 description_cond = description_cond),
Anand Doshi22c0d782013-11-04 16:23:04 +0530216 {
217 "today": nowdate(),
218 "txt": "%%%s%%" % txt,
Anand Doshi652bc072014-04-16 15:21:46 +0530219 "_txt": txt.replace("%", ""),
Anand Doshi22c0d782013-11-04 16:23:04 +0530220 "start": start,
221 "page_len": page_len
Rushabh Mehta203cc962016-04-07 15:25:43 +0530222 }, as_dict=as_dict)
Saurabh02875592013-07-08 18:45:55 +0530223
Saurabh022ab632017-11-10 15:06:02 +0530224def bom(doctype, txt, searchfield, start, page_len, filters):
Anand Doshibd67e872014-04-11 16:51:27 +0530225 conditions = []
Saurabhf52dc072013-07-10 13:07:49 +0530226
Anand Doshibd67e872014-04-11 16:51:27 +0530227 return frappe.db.sql("""select tabBOM.name, tabBOM.item
228 from tabBOM
229 where tabBOM.docstatus=1
230 and tabBOM.is_active=1
Nabin Hait62211172016-03-16 16:22:03 +0530231 and tabBOM.`{key}` like %(txt)s
232 {fcond} {mcond}
233 order by
Rushabh Mehta3574b372016-03-11 14:33:04 +0530234 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
235 idx desc, name
Nabin Hait62211172016-03-16 16:22:03 +0530236 limit %(start)s, %(page_len)s """.format(
Mangesh-Khairnar6a796912019-07-08 10:40:40 +0530237 fcond=get_filters_cond(doctype, filters, conditions).replace('%', '%%'),
Karthikeyan S747c2622019-07-19 22:49:21 +0530238 mcond=get_match_cond(doctype).replace('%', '%%'),
239 key=searchfield),
Mangesh-Khairnar6a796912019-07-08 10:40:40 +0530240 {
Karthikeyan S747c2622019-07-19 22:49:21 +0530241 'txt': '%' + txt + '%',
Rushabh Mehta3574b372016-03-11 14:33:04 +0530242 '_txt': txt.replace("%", ""),
Saurabh022ab632017-11-10 15:06:02 +0530243 'start': start or 0,
244 'page_len': page_len or 20
Rushabh Mehta3574b372016-03-11 14:33:04 +0530245 })
Saurabh02875592013-07-08 18:45:55 +0530246
Saurabh02875592013-07-08 18:45:55 +0530247def get_project_name(doctype, txt, searchfield, start, page_len, filters):
248 cond = ''
Nabin Haitf71011a2014-08-21 11:34:31 +0530249 if filters.get('customer'):
Suraj Shetty6ea3de92018-09-26 18:15:53 +0530250 cond = """(`tabProject`.customer = %s or
rohitwaghchauree3304722018-08-27 11:43:57 +0530251 ifnull(`tabProject`.customer,"")="") and""" %(frappe.db.escape(filters.get("customer")))
Anand Doshibd67e872014-04-11 16:51:27 +0530252
253 return frappe.db.sql("""select `tabProject`.name from `tabProject`
254 where `tabProject`.status not in ("Completed", "Cancelled")
Rushabh Mehta3574b372016-03-11 14:33:04 +0530255 and {cond} `tabProject`.name like %(txt)s {match_cond}
256 order by
257 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
258 idx desc,
259 `tabProject`.name asc
260 limit {start}, {page_len}""".format(
261 cond=cond,
262 match_cond=get_match_cond(doctype),
263 start=start,
264 page_len=page_len), {
265 "txt": "%{0}%".format(txt),
Nabin Haitdf4deba2016-03-16 11:16:31 +0530266 "_txt": txt.replace('%', '')
Rushabh Mehta3574b372016-03-11 14:33:04 +0530267 })
Anand Doshibd67e872014-04-11 16:51:27 +0530268
tundebabzyf6d738b2017-09-18 12:40:09 +0100269
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530270def get_delivery_notes_to_be_billed(doctype, txt, searchfield, start, page_len, filters, as_dict):
271 return frappe.db.sql("""
272 select `tabDelivery Note`.name, `tabDelivery Note`.customer, `tabDelivery Note`.posting_date
Anand Doshibd67e872014-04-11 16:51:27 +0530273 from `tabDelivery Note`
274 where `tabDelivery Note`.`%(key)s` like %(txt)s and
tundebabzyf6d738b2017-09-18 12:40:09 +0100275 `tabDelivery Note`.docstatus = 1
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530276 and status not in ("Stopped", "Closed") %(fcond)s
tundebabzyf6d738b2017-09-18 12:40:09 +0100277 and (
278 (`tabDelivery Note`.is_return = 0 and `tabDelivery Note`.per_billed < 100)
279 or `tabDelivery Note`.grand_total = 0
280 or (
281 `tabDelivery Note`.is_return = 1
282 and return_against in (select name from `tabDelivery Note` where per_billed < 100)
283 )
284 )
rohitwaghchaured07a3e12019-05-15 07:46:28 +0530285 %(mcond)s order by `tabDelivery Note`.`%(key)s` asc limit %(start)s, %(page_len)s
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530286 """ % {
287 "key": searchfield,
288 "fcond": get_filters_cond(doctype, filters, []),
289 "mcond": get_match_cond(doctype),
rohitwaghchaured07a3e12019-05-15 07:46:28 +0530290 "start": start,
291 "page_len": page_len,
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530292 "txt": "%(txt)s"
tundebabzyf6d738b2017-09-18 12:40:09 +0100293 }, {"txt": ("%%%s%%" % txt)}, as_dict=as_dict)
294
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530295
296def get_batch_no(doctype, txt, searchfield, start, page_len, filters):
Neil Trini Lasradoebb60f52015-07-08 14:36:09 +0530297 cond = ""
298 if filters.get("posting_date"):
Nabin Hait7918b922018-01-31 15:30:03 +0530299 cond = "and (batch.expiry_date is null or batch.expiry_date >= %(posting_date)s)"
Rushabh Mehtab6398be2015-08-26 10:50:16 +0530300
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530301 batch_nos = None
302 args = {
303 'item_code': filters.get("item_code"),
304 'warehouse': filters.get("warehouse"),
305 'posting_date': filters.get('posting_date'),
Anand Doshi0dc79f42015-04-06 12:59:34 +0530306 'txt': "%{0}%".format(txt),
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530307 "start": start,
308 "page_len": page_len
309 }
310
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530311 having_clause = "having sum(sle.actual_qty) > 0"
312 if filters.get("is_return"):
313 having_clause = ""
314
Anand Doshi0dc79f42015-04-06 12:59:34 +0530315 if args.get('warehouse'):
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530316 batch_nos = frappe.db.sql("""select sle.batch_no, round(sum(sle.actual_qty),2), sle.stock_uom,
317 concat('MFG-',batch.manufacturing_date), concat('EXP-',batch.expiry_date)
318 from `tabStock Ledger Entry` sle
319 INNER JOIN `tabBatch` batch on sle.batch_no = batch.name
320 where
321 batch.disabled = 0
322 and sle.item_code = %(item_code)s
323 and sle.warehouse = %(warehouse)s
324 and (sle.batch_no like %(txt)s
Sun Howwrongbum088be372019-12-24 12:29:25 +0530325 or batch.expiry_date like %(txt)s
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530326 or batch.manufacturing_date like %(txt)s)
327 and batch.docstatus < 2
328 {cond}
329 {match_conditions}
330 group by batch_no {having_clause}
331 order by batch.expiry_date, sle.batch_no desc
332 limit %(start)s, %(page_len)s""".format(
333 cond=cond,
334 match_conditions=get_match_cond(doctype),
335 having_clause = having_clause
336 ), args)
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530337
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530338 return batch_nos
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530339 else:
sivankar621740e2018-02-12 14:33:40 +0530340 return frappe.db.sql("""select name, concat('MFG-', manufacturing_date), concat('EXP-',expiry_date) from `tabBatch` batch
Doridel Cahanap59e4c322018-08-06 17:15:18 +0800341 where batch.disabled = 0
342 and item = %(item_code)s
sivankar621740e2018-02-12 14:33:40 +0530343 and (name like %(txt)s
Sun Howwrongbum088be372019-12-24 12:29:25 +0530344 or expiry_date like %(txt)s
sivankar621740e2018-02-12 14:33:40 +0530345 or manufacturing_date like %(txt)s)
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530346 and docstatus < 2
Neil Trini Lasradoebb60f52015-07-08 14:36:09 +0530347 {0}
Anand Doshi0dc79f42015-04-06 12:59:34 +0530348 {match_conditions}
349 order by expiry_date, name desc
Nabin Haite52ee552015-09-02 10:55:32 +0530350 limit %(start)s, %(page_len)s""".format(cond, match_conditions=get_match_cond(doctype)), args)
Nabin Haitea4aa042014-05-28 12:56:28 +0530351
352def get_account_list(doctype, txt, searchfield, start, page_len, filters):
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530353 filter_list = []
Nabin Haitea4aa042014-05-28 12:56:28 +0530354
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530355 if isinstance(filters, dict):
356 for key, val in filters.items():
357 if isinstance(val, (list, tuple)):
358 filter_list.append([doctype, key, val[0], val[1]])
359 else:
360 filter_list.append([doctype, key, "=", val])
bhupeshg2e2e973f2015-04-14 22:15:24 +0530361 elif isinstance(filters, list):
362 filter_list.extend(filters)
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530363
Rushabh Mehta38c6b522015-04-23 13:14:17 +0530364 if "is_group" not in [d[1] for d in filter_list]:
365 filter_list.append(["Account", "is_group", "=", "0"])
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530366
367 if searchfield and txt:
368 filter_list.append([doctype, searchfield, "like", "%%%s%%" % txt])
369
Rushabh Mehtac0bb4532014-09-09 16:15:35 +0530370 return frappe.desk.reportview.execute("Account", filters = filter_list,
Nabin Haitea4aa042014-05-28 12:56:28 +0530371 fields = ["name", "parent_account"],
372 limit_start=start, limit_page_length=page_len, as_list=True)
Anand Doshifaefeaa2014-06-24 18:53:04 +0530373
Maricaac98eb52020-04-28 13:00:44 +0530374def get_blanket_orders(doctype, txt, searchfield, start, page_len, filters):
375 return frappe.db.sql("""select distinct bo.name, bo.blanket_order_type, bo.to_date
376 from `tabBlanket Order` bo, `tabBlanket Order Item` boi
377 where
378 boi.parent = bo.name
379 and boi.item_code = {item_code}
380 and bo.blanket_order_type = '{blanket_order_type}'
381 and bo.company = {company}
382 and bo.docstatus = 1"""
383 .format(item_code = frappe.db.escape(filters.get("item")),
384 blanket_order_type = filters.get("blanket_order_type"),
385 company = frappe.db.escape(filters.get("company"))
386 ))
Nabin Haitafd14f62015-10-19 11:55:28 +0530387
388@frappe.whitelist()
389def get_income_account(doctype, txt, searchfield, start, page_len, filters):
390 from erpnext.controllers.queries import get_match_cond
391
392 # income account can be any Credit account,
393 # but can also be a Asset account with account_type='Income Account' in special circumstances.
394 # Hence the first condition is an "OR"
395 if not filters: filters = {}
396
Anand Doshi21e09a22015-10-29 12:21:41 +0530397 condition = ""
Nabin Haitafd14f62015-10-19 11:55:28 +0530398 if filters.get("company"):
399 condition += "and tabAccount.company = %(company)s"
Anand Doshi21e09a22015-10-29 12:21:41 +0530400
Nabin Haitafd14f62015-10-19 11:55:28 +0530401 return frappe.db.sql("""select tabAccount.name from `tabAccount`
402 where (tabAccount.report_type = "Profit and Loss"
403 or tabAccount.account_type in ("Income Account", "Temporary"))
404 and tabAccount.is_group=0
405 and tabAccount.`{key}` LIKE %(txt)s
Rushabh Mehta3574b372016-03-11 14:33:04 +0530406 {condition} {match_condition}
407 order by idx desc, name"""
Nabin Haitafd14f62015-10-19 11:55:28 +0530408 .format(condition=condition, match_condition=get_match_cond(doctype), key=searchfield), {
Suraj Shetty4b404c42018-09-27 15:39:34 +0530409 'txt': '%' + txt + '%',
Nabin Haitafd14f62015-10-19 11:55:28 +0530410 'company': filters.get("company", "")
Anand Doshi21e09a22015-10-29 12:21:41 +0530411 })
Nabin Hait3a15c922016-03-04 12:30:46 +0530412
413
414@frappe.whitelist()
415def get_expense_account(doctype, txt, searchfield, start, page_len, filters):
416 from erpnext.controllers.queries import get_match_cond
Rushabh Mehta203cc962016-04-07 15:25:43 +0530417
Nabin Hait3a15c922016-03-04 12:30:46 +0530418 if not filters: filters = {}
419
420 condition = ""
421 if filters.get("company"):
422 condition += "and tabAccount.company = %(company)s"
Rushabh Mehta203cc962016-04-07 15:25:43 +0530423
Nabin Hait3a15c922016-03-04 12:30:46 +0530424 return frappe.db.sql("""select tabAccount.name from `tabAccount`
425 where (tabAccount.report_type = "Profit and Loss"
Mangesh-Khairnar5619db22019-08-21 14:49:24 +0530426 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 +0530427 and tabAccount.is_group=0
428 and tabAccount.docstatus!=2
429 and tabAccount.{key} LIKE %(txt)s
430 {condition} {match_condition}"""
Suraj Shettybfc195d2018-09-21 10:20:52 +0530431 .format(condition=condition, key=searchfield,
Nabin Hait3a15c922016-03-04 12:30:46 +0530432 match_condition=get_match_cond(doctype)), {
Neil Trini Lasrado30b97b02016-03-31 23:10:13 +0530433 'company': filters.get("company", ""),
Suraj Shetty4b404c42018-09-27 15:39:34 +0530434 'txt': '%' + txt + '%'
Maxwell Morais35572612016-07-21 23:42:59 -0300435 })
suyashphadtare049a88c2017-01-12 17:49:37 +0530436
437
438@frappe.whitelist()
439def warehouse_query(doctype, txt, searchfield, start, page_len, filters):
440 # Should be used when item code is passed in filters.
suyashphadtare750a0672017-01-18 15:35:01 +0530441 conditions, bin_conditions = [], []
442 filter_dict = get_doctype_wise_filters(filters)
443
444 sub_query = """ select round(`tabBin`.actual_qty, 2) from `tabBin`
suyashphadtare34ab1362017-01-31 15:14:44 +0530445 where `tabBin`.warehouse = `tabWarehouse`.name
446 {bin_conditions} """.format(
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530447 bin_conditions=get_filters_cond(doctype, filter_dict.get("Bin"),
Nabin Hait4e6ff8c2017-05-09 15:09:10 +0530448 bin_conditions, ignore_permissions=True))
suyashphadtare750a0672017-01-18 15:35:01 +0530449
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530450 query = """select `tabWarehouse`.name,
suyashphadtare34ab1362017-01-31 15:14:44 +0530451 CONCAT_WS(" : ", "Actual Qty", ifnull( ({sub_query}), 0) ) as actual_qty
452 from `tabWarehouse`
453 where
Suraj Shetty6ea3de92018-09-26 18:15:53 +0530454 `tabWarehouse`.`{key}` like {txt}
suyashphadtare34ab1362017-01-31 15:14:44 +0530455 {fcond} {mcond}
456 order by
457 `tabWarehouse`.name desc
458 limit
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530459 {start}, {page_len}
suyashphadtare34ab1362017-01-31 15:14:44 +0530460 """.format(
461 sub_query=sub_query,
Suraj Shettybfc195d2018-09-21 10:20:52 +0530462 key=searchfield,
suyashphadtare34ab1362017-01-31 15:14:44 +0530463 fcond=get_filters_cond(doctype, filter_dict.get("Warehouse"), conditions),
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530464 mcond=get_match_cond(doctype),
465 start=start,
466 page_len=page_len,
467 txt=frappe.db.escape('%{0}%'.format(txt))
468 )
469
470 return frappe.db.sql(query)
suyashphadtare750a0672017-01-18 15:35:01 +0530471
472
473def get_doctype_wise_filters(filters):
474 # Helper function to seperate filters doctype_wise
475 filter_dict = defaultdict(list)
476 for row in filters:
477 filter_dict[row[0]].append(row)
478 return filter_dict
tundebabzy2a4fefc2017-11-29 06:23:09 +0100479
480
481@frappe.whitelist()
482def get_batch_numbers(doctype, txt, searchfield, start, page_len, filters):
rohitwaghchaure9fbed562018-01-12 16:22:33 +0530483 query = """select batch_id from `tabBatch`
Doridel Cahanap59e4c322018-08-06 17:15:18 +0800484 where disabled = 0
485 and (expiry_date >= CURDATE() or expiry_date IS NULL)
Suraj Shettybfc195d2018-09-21 10:20:52 +0530486 and name like {txt}""".format(txt = frappe.db.escape('%{0}%'.format(txt)))
tundebabzy2a4fefc2017-11-29 06:23:09 +0100487
rohitwaghchaure9fbed562018-01-12 16:22:33 +0530488 if filters and filters.get('item'):
Suraj Shettybfc195d2018-09-21 10:20:52 +0530489 query += " and item = {item}".format(item = frappe.db.escape(filters.get('item')))
tundebabzy2a4fefc2017-11-29 06:23:09 +0100490
Sachin Mane64f48db2018-01-08 17:57:32 +0530491 return frappe.db.sql(query, filters)
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530492
493@frappe.whitelist()
494def item_manufacturer_query(doctype, txt, searchfield, start, page_len, filters):
Maricabac4b932019-09-16 19:44:28 +0530495 item_filters = [
496 ['manufacturer', 'like', '%' + txt + '%'],
497 ['item_code', '=', filters.get("item_code")]
498 ]
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530499
Maricabac4b932019-09-16 19:44:28 +0530500 item_manufacturers = frappe.get_all(
501 "Item Manufacturer",
502 fields=["manufacturer", "manufacturer_part_no"],
503 filters=item_filters,
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530504 limit_start=start,
505 limit_page_length=page_len,
506 as_list=1
507 )
Maricabac4b932019-09-16 19:44:28 +0530508 return item_manufacturers
Saqibd9956092019-11-18 11:46:55 +0530509
510@frappe.whitelist()
511def get_purchase_receipts(doctype, txt, searchfield, start, page_len, filters):
512 query = """
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530513 select pr.name
Saqibd9956092019-11-18 11:46:55 +0530514 from `tabPurchase Receipt` pr, `tabPurchase Receipt Item` pritem
515 where pr.docstatus = 1 and pritem.parent = pr.name
516 and pr.name like {txt}""".format(txt = frappe.db.escape('%{0}%'.format(txt)))
517
518 if filters and filters.get('item_code'):
519 query += " and pritem.item_code = {item_code}".format(item_code = frappe.db.escape(filters.get('item_code')))
520
521 return frappe.db.sql(query, filters)
522
523@frappe.whitelist()
524def get_purchase_invoices(doctype, txt, searchfield, start, page_len, filters):
525 query = """
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530526 select pi.name
Saqibd9956092019-11-18 11:46:55 +0530527 from `tabPurchase Invoice` pi, `tabPurchase Invoice Item` piitem
528 where pi.docstatus = 1 and piitem.parent = pi.name
529 and pi.name like {txt}""".format(txt = frappe.db.escape('%{0}%'.format(txt)))
530
531 if filters and filters.get('item_code'):
532 query += " and piitem.item_code = {item_code}".format(item_code = frappe.db.escape(filters.get('item_code')))
533
534 return frappe.db.sql(query, filters)
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530535
536@frappe.whitelist()
537def get_tax_template(doctype, txt, searchfield, start, page_len, filters):
538
539 item_doc = frappe.get_cached_doc('Item', filters.get('item_code'))
540 item_group = filters.get('item_group')
541 taxes = item_doc.taxes or []
542
543 while item_group:
544 item_group_doc = frappe.get_cached_doc('Item Group', item_group)
545 taxes += item_group_doc.taxes or []
546 item_group = item_group_doc.parent_item_group
547
548 if not taxes:
549 return frappe.db.sql(""" SELECT name FROM `tabItem Tax Template` """)
550 else:
551 args = {
552 'item_code': filters.get('item_code'),
553 'posting_date': filters.get('valid_from'),
554 'tax_category': filters.get('tax_category')
555 }
556
557 taxes = _get_item_tax_template(args, taxes, for_validate=True)
558 return [(d,) for d in set(taxes)]