blob: d870823ad1d381c501c91afa80760898fb03f8e9 [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
Chillar Anand915b3432021-09-02 16:44:59 +05304
rohitwaghchaurec59371a2021-06-03 20:02:58 +05305import json
suyashphadtare750a0672017-01-18 15:35:01 +05306from collections import defaultdict
Chillar Anand915b3432021-09-02 16:44:59 +05307
8import frappe
DeeMysterioaa826242021-09-14 13:58:18 +05309from frappe import scrub
Chillar Anand915b3432021-09-02 16:44:59 +053010from frappe.desk.reportview import get_filters_cond, get_match_cond
11from frappe.utils import nowdate, unique
12
13import erpnext
Deepesh Gargef0d26c2020-01-06 15:34:15 +053014from erpnext.stock.get_item_details import _get_item_tax_template
Chillar Anand915b3432021-09-02 16:44:59 +053015
Saurabh02875592013-07-08 18:45:55 +053016
Chinmay D. Paiaa121092020-07-01 21:14:32 +053017# searches for active employees
18@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +053019@frappe.validate_and_sanitize_search_inputs
Saurabh02875592013-07-08 18:45:55 +053020def employee_query(doctype, txt, searchfield, start, page_len, filters):
Kanchan Chauhan7652b852016-11-16 15:29:01 +053021 conditions = []
Himanshud94a38e2020-05-18 14:26:26 +053022 fields = get_fields("Employee", ["name", "employee_name"])
23
24 return frappe.db.sql("""select {fields} from `tabEmployee`
Anurag Mishrafc98abe2021-06-23 11:21:38 +053025 where status in ('Active', 'Suspended')
Anand Doshibd67e872014-04-11 16:51:27 +053026 and docstatus < 2
Anand Doshi48d3b542014-07-09 13:15:03 +053027 and ({key} like %(txt)s
28 or employee_name like %(txt)s)
Kanchan Chauhan7652b852016-11-16 15:29:01 +053029 {fcond} {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +053030 order by
Anand Doshi48d3b542014-07-09 13:15:03 +053031 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
32 if(locate(%(_txt)s, employee_name), locate(%(_txt)s, employee_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +053033 idx desc,
Anand Doshi652bc072014-04-16 15:21:46 +053034 name, employee_name
Anand Doshi48d3b542014-07-09 13:15:03 +053035 limit %(start)s, %(page_len)s""".format(**{
Himanshud94a38e2020-05-18 14:26:26 +053036 'fields': ", ".join(fields),
Anand Doshi48d3b542014-07-09 13:15:03 +053037 'key': searchfield,
Kanchan Chauhan7652b852016-11-16 15:29:01 +053038 'fcond': get_filters_cond(doctype, filters, conditions),
Anand Doshi48d3b542014-07-09 13:15:03 +053039 'mcond': get_match_cond(doctype)
40 }), {
41 'txt': "%%%s%%" % txt,
42 '_txt': txt.replace("%", ""),
43 'start': start,
44 'page_len': page_len
45 })
Saurabh02875592013-07-08 18:45:55 +053046
Himanshud94a38e2020-05-18 14:26:26 +053047
48# searches for leads which are not converted
Chinmay D. Paiaa121092020-07-01 21:14:32 +053049@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +053050@frappe.validate_and_sanitize_search_inputs
Anand Doshibd67e872014-04-11 16:51:27 +053051def lead_query(doctype, txt, searchfield, start, page_len, filters):
Himanshud94a38e2020-05-18 14:26:26 +053052 fields = get_fields("Lead", ["name", "lead_name", "company_name"])
53
54 return frappe.db.sql("""select {fields} from `tabLead`
Anand Doshibd67e872014-04-11 16:51:27 +053055 where docstatus < 2
56 and ifnull(status, '') != 'Converted'
Anand Doshi48d3b542014-07-09 13:15:03 +053057 and ({key} like %(txt)s
58 or lead_name like %(txt)s
59 or company_name like %(txt)s)
60 {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +053061 order by
Anand Doshi48d3b542014-07-09 13:15:03 +053062 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
63 if(locate(%(_txt)s, lead_name), locate(%(_txt)s, lead_name), 99999),
64 if(locate(%(_txt)s, company_name), locate(%(_txt)s, company_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +053065 idx desc,
Anand Doshi652bc072014-04-16 15:21:46 +053066 name, lead_name
Anand Doshi48d3b542014-07-09 13:15:03 +053067 limit %(start)s, %(page_len)s""".format(**{
Himanshud94a38e2020-05-18 14:26:26 +053068 'fields': ", ".join(fields),
Anand Doshi48d3b542014-07-09 13:15:03 +053069 'key': searchfield,
70 'mcond':get_match_cond(doctype)
71 }), {
72 'txt': "%%%s%%" % txt,
73 '_txt': txt.replace("%", ""),
74 'start': start,
75 'page_len': page_len
76 })
Saurabh02875592013-07-08 18:45:55 +053077
Himanshud94a38e2020-05-18 14:26:26 +053078
Saurabh02875592013-07-08 18:45:55 +053079 # searches for customer
Chinmay D. Paiaa121092020-07-01 21:14:32 +053080@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +053081@frappe.validate_and_sanitize_search_inputs
Saurabh02875592013-07-08 18:45:55 +053082def customer_query(doctype, txt, searchfield, start, page_len, filters):
KanchanChauhan4b888b92017-07-25 14:03:01 +053083 conditions = []
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053084 cust_master_name = frappe.defaults.get_user_default("cust_master_name")
Saurabhf52dc072013-07-10 13:07:49 +053085
Saurabh02875592013-07-08 18:45:55 +053086 if cust_master_name == "Customer Name":
87 fields = ["name", "customer_group", "territory"]
88 else:
89 fields = ["name", "customer_name", "customer_group", "territory"]
Rushabh Mehtab92087c2017-01-13 18:53:11 +053090
Himanshud94a38e2020-05-18 14:26:26 +053091 fields = get_fields("Customer", fields)
Saurabhf52dc072013-07-10 13:07:49 +053092
Himanshud94a38e2020-05-18 14:26:26 +053093 searchfields = frappe.get_meta("Customer").get_search_fields()
Ankush Menata9c84f72021-06-11 16:00:48 +053094 searchfields = " or ".join(field + " like %(txt)s" for field in searchfields)
Saurabh02875592013-07-08 18:45:55 +053095
Anand Doshi48d3b542014-07-09 13:15:03 +053096 return frappe.db.sql("""select {fields} from `tabCustomer`
Anand Doshibd67e872014-04-11 16:51:27 +053097 where docstatus < 2
Console Admin86231662017-06-23 20:32:52 +030098 and ({scond}) and disabled=0
KanchanChauhan4b888b92017-07-25 14:03:01 +053099 {fcond} {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +0530100 order by
Anand Doshi48d3b542014-07-09 13:15:03 +0530101 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
102 if(locate(%(_txt)s, customer_name), locate(%(_txt)s, customer_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530103 idx desc,
Anand Doshibd67e872014-04-11 16:51:27 +0530104 name, customer_name
Anand Doshi48d3b542014-07-09 13:15:03 +0530105 limit %(start)s, %(page_len)s""".format(**{
Himanshud94a38e2020-05-18 14:26:26 +0530106 "fields": ", ".join(fields),
Console Admin86231662017-06-23 20:32:52 +0300107 "scond": searchfields,
KanchanChauhan4b888b92017-07-25 14:03:01 +0530108 "mcond": get_match_cond(doctype),
109 "fcond": get_filters_cond(doctype, filters, conditions).replace('%', '%%'),
Anand Doshi48d3b542014-07-09 13:15:03 +0530110 }), {
111 'txt': "%%%s%%" % txt,
112 '_txt': txt.replace("%", ""),
113 'start': start,
114 'page_len': page_len
115 })
Saurabh02875592013-07-08 18:45:55 +0530116
Himanshud94a38e2020-05-18 14:26:26 +0530117
Saurabh02875592013-07-08 18:45:55 +0530118# searches for supplier
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530119@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530120@frappe.validate_and_sanitize_search_inputs
Saurabh02875592013-07-08 18:45:55 +0530121def supplier_query(doctype, txt, searchfield, start, page_len, filters):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530122 supp_master_name = frappe.defaults.get_user_default("supp_master_name")
Suraj Shetty1923ef02020-08-05 19:42:25 +0530123
Anand Doshibd67e872014-04-11 16:51:27 +0530124 if supp_master_name == "Supplier Name":
Zlash652e080982018-04-19 18:37:53 +0530125 fields = ["name", "supplier_group"]
Anand Doshibd67e872014-04-11 16:51:27 +0530126 else:
Zlash652e080982018-04-19 18:37:53 +0530127 fields = ["name", "supplier_name", "supplier_group"]
Himanshud94a38e2020-05-18 14:26:26 +0530128
129 fields = get_fields("Supplier", fields)
Saurabh02875592013-07-08 18:45:55 +0530130
Anand Doshi48d3b542014-07-09 13:15:03 +0530131 return frappe.db.sql("""select {field} from `tabSupplier`
Anand Doshibd67e872014-04-11 16:51:27 +0530132 where docstatus < 2
Anand Doshi48d3b542014-07-09 13:15:03 +0530133 and ({key} like %(txt)s
Ankush Menat2221c9e2021-10-27 19:15:44 +0530134 or supplier_name like %(txt)s) and disabled=0
135 and (on_hold = 0 or (on_hold = 1 and CURDATE() > release_date))
Anand Doshi48d3b542014-07-09 13:15:03 +0530136 {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +0530137 order by
Anand Doshi48d3b542014-07-09 13:15:03 +0530138 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
139 if(locate(%(_txt)s, supplier_name), locate(%(_txt)s, supplier_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530140 idx desc,
Anand Doshibd67e872014-04-11 16:51:27 +0530141 name, supplier_name
Anand Doshi48d3b542014-07-09 13:15:03 +0530142 limit %(start)s, %(page_len)s """.format(**{
Himanshud94a38e2020-05-18 14:26:26 +0530143 'field': ', '.join(fields),
Anand Doshi48d3b542014-07-09 13:15:03 +0530144 'key': searchfield,
145 'mcond':get_match_cond(doctype)
146 }), {
147 'txt': "%%%s%%" % txt,
148 '_txt': txt.replace("%", ""),
149 'start': start,
150 'page_len': page_len
151 })
Anand Doshibd67e872014-04-11 16:51:27 +0530152
Himanshud94a38e2020-05-18 14:26:26 +0530153
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530154@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530155@frappe.validate_and_sanitize_search_inputs
Nabin Hait9a380ef2013-07-16 17:24:17 +0530156def tax_account_query(doctype, txt, searchfield, start, page_len, filters):
Deepesh Gargfbf6e562020-03-31 10:45:32 +0530157 company_currency = erpnext.get_company_currency(filters.get('company'))
158
Suraj Shetty1923ef02020-08-05 19:42:25 +0530159 def get_accounts(with_account_type_filter):
160 account_type_condition = ''
161 if with_account_type_filter:
162 account_type_condition = "AND account_type in %(account_types)s"
163
164 accounts = frappe.db.sql("""
165 SELECT name, parent_account
166 FROM `tabAccount`
167 WHERE `tabAccount`.docstatus!=2
168 {account_type_condition}
169 AND is_group = 0
170 AND company = %(company)s
Deepesh Garg57924592022-03-22 18:26:58 +0530171 AND (account_currency = %(currency)s or ifnull(account_currency, '') = '')
Suraj Shetty1923ef02020-08-05 19:42:25 +0530172 AND `{searchfield}` LIKE %(txt)s
prssannade7a2bc2020-09-21 13:57:04 +0530173 {mcond}
Suraj Shetty1923ef02020-08-05 19:42:25 +0530174 ORDER BY idx DESC, name
175 LIMIT %(offset)s, %(limit)s
prssannade7a2bc2020-09-21 13:57:04 +0530176 """.format(
177 account_type_condition=account_type_condition,
178 searchfield=searchfield,
179 mcond=get_match_cond(doctype)
180 ),
Suraj Shetty1923ef02020-08-05 19:42:25 +0530181 dict(
182 account_types=filters.get("account_type"),
183 company=filters.get("company"),
184 currency=company_currency,
185 txt="%{}%".format(txt),
186 offset=start,
187 limit=page_len
188 )
189 )
190
191 return accounts
192
193 tax_accounts = get_accounts(True)
194
Nabin Hait0c21e2a2014-03-21 11:14:49 +0530195 if not tax_accounts:
Suraj Shetty1923ef02020-08-05 19:42:25 +0530196 tax_accounts = get_accounts(False)
Anand Doshibd67e872014-04-11 16:51:27 +0530197
Nabin Hait0c21e2a2014-03-21 11:14:49 +0530198 return tax_accounts
Saurabh02875592013-07-08 18:45:55 +0530199
Himanshud94a38e2020-05-18 14:26:26 +0530200
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530201@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530202@frappe.validate_and_sanitize_search_inputs
Rushabh Mehta203cc962016-04-07 15:25:43 +0530203def item_query(doctype, txt, searchfield, start, page_len, filters, as_dict=False):
Saurabh02875592013-07-08 18:45:55 +0530204 conditions = []
Saurabhf52dc072013-07-10 13:07:49 +0530205
rohitwaghchaurec59371a2021-06-03 20:02:58 +0530206 if isinstance(filters, str):
207 filters = json.loads(filters)
208
marination3dbef9d2019-10-28 15:48:10 +0530209 #Get searchfields from meta and use in Item Link field query
marination1e754b12019-10-30 18:33:44 +0530210 meta = frappe.get_meta("Item", cached=True)
marination3dbef9d2019-10-28 15:48:10 +0530211 searchfields = meta.get_search_fields()
212
Ankush Menat34f52832021-11-09 11:55:33 +0530213 # these are handled separately
214 ignored_search_fields = ("item_name", "description")
215 for ignored_field in ignored_search_fields:
216 if ignored_field in searchfields:
217 searchfields.remove(ignored_field)
Rohit Waghchaure721b4132021-06-02 14:13:09 +0530218
Rohit Waghchaurec42312e2019-11-19 19:05:23 +0530219 columns = ''
220 extra_searchfields = [field for field in searchfields
Ankush Menat34f52832021-11-09 11:55:33 +0530221 if not field in ["name", "item_group", "description", "item_name"]]
Rohit Waghchaurec42312e2019-11-19 19:05:23 +0530222
223 if extra_searchfields:
224 columns = ", " + ", ".join(extra_searchfields)
marination1e754b12019-10-30 18:33:44 +0530225
226 searchfields = searchfields + [field for field in[searchfield or "name", "item_code", "item_group", "item_name"]
227 if not field in searchfields]
marination3dbef9d2019-10-28 15:48:10 +0530228 searchfields = " or ".join([field + " like %(txt)s" for field in searchfields])
229
DeeMysterioaa826242021-09-14 13:58:18 +0530230 if filters and isinstance(filters, dict):
231 if filters.get('customer') or filters.get('supplier'):
232 party = filters.get('customer') or filters.get('supplier')
233 item_rules_list = frappe.get_all('Party Specific Item',
234 filters = {'party': party}, fields = ['restrict_based_on', 'based_on_value'])
Rohit Waghchaure721b4132021-06-02 14:13:09 +0530235
DeeMysterioaa826242021-09-14 13:58:18 +0530236 filters_dict = {}
237 for rule in item_rules_list:
238 if rule['restrict_based_on'] == 'Item':
239 rule['restrict_based_on'] = 'name'
240 filters_dict[rule.restrict_based_on] = []
noahjacobca2fb472021-05-12 16:25:07 +0530241
DeeMysterioaa826242021-09-14 13:58:18 +0530242 for rule in item_rules_list:
243 filters_dict[rule.restrict_based_on].append(rule.based_on_value)
noahjacobca2fb472021-05-12 16:25:07 +0530244
DeeMysterioaa826242021-09-14 13:58:18 +0530245 for filter in filters_dict:
246 filters[scrub(filter)] = ['in', filters_dict[filter]]
247
248 if filters.get('customer'):
249 del filters['customer']
250 else:
251 del filters['supplier']
Ankush Menat41a95e52022-02-03 13:02:13 +0530252 else:
253 filters.pop('customer', None)
254 filters.pop('supplier', None)
DeeMysterioaa826242021-09-14 13:58:18 +0530255
Rohit Waghchaure721b4132021-06-02 14:13:09 +0530256
Rushabh Mehtad5f9ebd2018-04-02 23:37:33 +0530257 description_cond = ''
258 if frappe.db.count('Item', cache=True) < 50000:
259 # scan description only if items are less than 50000
260 description_cond = 'or tabItem.description LIKE %(txt)s'
Ankush Menat34f52832021-11-09 11:55:33 +0530261 return frappe.db.sql("""select
262 tabItem.name, tabItem.item_name, tabItem.item_group,
Saurabh02875592013-07-08 18:45:55 +0530263 if(length(tabItem.description) > 40, \
Rohit Waghchaurec42312e2019-11-19 19:05:23 +0530264 concat(substr(tabItem.description, 1, 40), "..."), description) as description
marination1e754b12019-10-30 18:33:44 +0530265 {columns}
Anand Doshibd67e872014-04-11 16:51:27 +0530266 from tabItem
Anand Doshi22c0d782013-11-04 16:23:04 +0530267 where tabItem.docstatus < 2
Anand Doshi21e09a22015-10-29 12:21:41 +0530268 and tabItem.disabled=0
rohitwaghchaure79789072020-05-21 18:10:13 +0530269 and tabItem.has_variants=0
Rushabh Mehta864d1ea2014-06-23 12:20:12 +0530270 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 +0530271 and ({scond} or tabItem.item_code IN (select parent from `tabItem Barcode` where barcode LIKE %(txt)s)
Rohit Waghchaure2bfb0632019-03-02 21:47:55 +0530272 {description_cond})
Anand Doshi22c0d782013-11-04 16:23:04 +0530273 {fcond} {mcond}
Anand Doshi652bc072014-04-16 15:21:46 +0530274 order by
275 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
276 if(locate(%(_txt)s, item_name), locate(%(_txt)s, item_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530277 idx desc,
Anand Doshi652bc072014-04-16 15:21:46 +0530278 name, item_name
Rushabh Mehtabc4e2cd2017-10-17 12:30:34 +0530279 limit %(start)s, %(page_len)s """.format(
marination1e754b12019-10-30 18:33:44 +0530280 columns=columns,
marination3dbef9d2019-10-28 15:48:10 +0530281 scond=searchfields,
Nabin Haitc6285062016-03-30 13:10:25 +0530282 fcond=get_filters_cond(doctype, filters, conditions).replace('%', '%%'),
Rushabh Mehtad5f9ebd2018-04-02 23:37:33 +0530283 mcond=get_match_cond(doctype).replace('%', '%%'),
284 description_cond = description_cond),
Anand Doshi22c0d782013-11-04 16:23:04 +0530285 {
286 "today": nowdate(),
287 "txt": "%%%s%%" % txt,
Anand Doshi652bc072014-04-16 15:21:46 +0530288 "_txt": txt.replace("%", ""),
Anand Doshi22c0d782013-11-04 16:23:04 +0530289 "start": start,
290 "page_len": page_len
Rushabh Mehta203cc962016-04-07 15:25:43 +0530291 }, as_dict=as_dict)
Saurabh02875592013-07-08 18:45:55 +0530292
Himanshud94a38e2020-05-18 14:26:26 +0530293
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530294@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530295@frappe.validate_and_sanitize_search_inputs
Saurabh022ab632017-11-10 15:06:02 +0530296def bom(doctype, txt, searchfield, start, page_len, filters):
Anand Doshibd67e872014-04-11 16:51:27 +0530297 conditions = []
Himanshud94a38e2020-05-18 14:26:26 +0530298 fields = get_fields("BOM", ["name", "item"])
Saurabhf52dc072013-07-10 13:07:49 +0530299
Himanshud94a38e2020-05-18 14:26:26 +0530300 return frappe.db.sql("""select {fields}
Anand Doshibd67e872014-04-11 16:51:27 +0530301 from tabBOM
302 where tabBOM.docstatus=1
303 and tabBOM.is_active=1
Nabin Hait62211172016-03-16 16:22:03 +0530304 and tabBOM.`{key}` like %(txt)s
305 {fcond} {mcond}
306 order by
Rushabh Mehta3574b372016-03-11 14:33:04 +0530307 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
308 idx desc, name
Nabin Hait62211172016-03-16 16:22:03 +0530309 limit %(start)s, %(page_len)s """.format(
Himanshud94a38e2020-05-18 14:26:26 +0530310 fields=", ".join(fields),
Mangesh-Khairnar6a796912019-07-08 10:40:40 +0530311 fcond=get_filters_cond(doctype, filters, conditions).replace('%', '%%'),
Karthikeyan S747c2622019-07-19 22:49:21 +0530312 mcond=get_match_cond(doctype).replace('%', '%%'),
313 key=searchfield),
Mangesh-Khairnar6a796912019-07-08 10:40:40 +0530314 {
Karthikeyan S747c2622019-07-19 22:49:21 +0530315 'txt': '%' + txt + '%',
Rushabh Mehta3574b372016-03-11 14:33:04 +0530316 '_txt': txt.replace("%", ""),
Saurabh022ab632017-11-10 15:06:02 +0530317 'start': start or 0,
318 'page_len': page_len or 20
Rushabh Mehta3574b372016-03-11 14:33:04 +0530319 })
Saurabh02875592013-07-08 18:45:55 +0530320
Himanshud94a38e2020-05-18 14:26:26 +0530321
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530322@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530323@frappe.validate_and_sanitize_search_inputs
Saurabh02875592013-07-08 18:45:55 +0530324def get_project_name(doctype, txt, searchfield, start, page_len, filters):
325 cond = ''
Ankush Menat62fc5442021-09-10 12:46:35 +0530326 if filters and filters.get('customer'):
Suraj Shetty6ea3de92018-09-26 18:15:53 +0530327 cond = """(`tabProject`.customer = %s or
rohitwaghchauree3304722018-08-27 11:43:57 +0530328 ifnull(`tabProject`.customer,"")="") and""" %(frappe.db.escape(filters.get("customer")))
Anand Doshibd67e872014-04-11 16:51:27 +0530329
Rucha Mahabal062d3012021-05-07 13:31:14 +0530330 fields = get_fields("Project", ["name", "project_name"])
331 searchfields = frappe.get_meta("Project").get_search_fields()
332 searchfields = " or ".join([field + " like %(txt)s" for field in searchfields])
Himanshud94a38e2020-05-18 14:26:26 +0530333
334 return frappe.db.sql("""select {fields} from `tabProject`
Rucha Mahabal062d3012021-05-07 13:31:14 +0530335 where
336 `tabProject`.status not in ("Completed", "Cancelled")
Subin Tom889140f2021-06-22 16:26:19 +0530337 and {cond} {scond} {match_cond}
Rushabh Mehta3574b372016-03-11 14:33:04 +0530338 order by
339 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
340 idx desc,
341 `tabProject`.name asc
342 limit {start}, {page_len}""".format(
Himanshud94a38e2020-05-18 14:26:26 +0530343 fields=", ".join(['`tabProject`.{0}'.format(f) for f in fields]),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530344 cond=cond,
Rucha Mahabal062d3012021-05-07 13:31:14 +0530345 scond=searchfields,
Rushabh Mehta3574b372016-03-11 14:33:04 +0530346 match_cond=get_match_cond(doctype),
347 start=start,
348 page_len=page_len), {
349 "txt": "%{0}%".format(txt),
Nabin Haitdf4deba2016-03-16 11:16:31 +0530350 "_txt": txt.replace('%', '')
Rushabh Mehta3574b372016-03-11 14:33:04 +0530351 })
Anand Doshibd67e872014-04-11 16:51:27 +0530352
tundebabzyf6d738b2017-09-18 12:40:09 +0100353
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530354@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530355@frappe.validate_and_sanitize_search_inputs
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530356def get_delivery_notes_to_be_billed(doctype, txt, searchfield, start, page_len, filters, as_dict):
Himanshud94a38e2020-05-18 14:26:26 +0530357 fields = get_fields("Delivery Note", ["name", "customer", "posting_date"])
358
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530359 return frappe.db.sql("""
Himanshud94a38e2020-05-18 14:26:26 +0530360 select %(fields)s
Anand Doshibd67e872014-04-11 16:51:27 +0530361 from `tabDelivery Note`
362 where `tabDelivery Note`.`%(key)s` like %(txt)s and
tundebabzyf6d738b2017-09-18 12:40:09 +0100363 `tabDelivery Note`.docstatus = 1
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530364 and status not in ("Stopped", "Closed") %(fcond)s
tundebabzyf6d738b2017-09-18 12:40:09 +0100365 and (
366 (`tabDelivery Note`.is_return = 0 and `tabDelivery Note`.per_billed < 100)
Deepesh Garge2dc1022021-04-14 11:21:11 +0530367 or (`tabDelivery Note`.grand_total = 0 and `tabDelivery Note`.per_billed < 100)
tundebabzyf6d738b2017-09-18 12:40:09 +0100368 or (
369 `tabDelivery Note`.is_return = 1
370 and return_against in (select name from `tabDelivery Note` where per_billed < 100)
371 )
372 )
rohitwaghchaured07a3e12019-05-15 07:46:28 +0530373 %(mcond)s order by `tabDelivery Note`.`%(key)s` asc limit %(start)s, %(page_len)s
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530374 """ % {
Himanshud94a38e2020-05-18 14:26:26 +0530375 "fields": ", ".join(["`tabDelivery Note`.{0}".format(f) for f in fields]),
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530376 "key": searchfield,
377 "fcond": get_filters_cond(doctype, filters, []),
378 "mcond": get_match_cond(doctype),
rohitwaghchaured07a3e12019-05-15 07:46:28 +0530379 "start": start,
380 "page_len": page_len,
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530381 "txt": "%(txt)s"
tundebabzyf6d738b2017-09-18 12:40:09 +0100382 }, {"txt": ("%%%s%%" % txt)}, as_dict=as_dict)
383
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530384
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530385@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530386@frappe.validate_and_sanitize_search_inputs
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530387def get_batch_no(doctype, txt, searchfield, start, page_len, filters):
Neil Trini Lasradoebb60f52015-07-08 14:36:09 +0530388 cond = ""
389 if filters.get("posting_date"):
Nabin Hait7918b922018-01-31 15:30:03 +0530390 cond = "and (batch.expiry_date is null or batch.expiry_date >= %(posting_date)s)"
Rushabh Mehtab6398be2015-08-26 10:50:16 +0530391
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530392 batch_nos = None
393 args = {
394 'item_code': filters.get("item_code"),
395 'warehouse': filters.get("warehouse"),
396 'posting_date': filters.get('posting_date'),
Anand Doshi0dc79f42015-04-06 12:59:34 +0530397 'txt': "%{0}%".format(txt),
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530398 "start": start,
399 "page_len": page_len
400 }
401
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530402 having_clause = "having sum(sle.actual_qty) > 0"
403 if filters.get("is_return"):
404 having_clause = ""
405
Deepesh Garga0d192e2020-09-22 13:54:07 +0530406 meta = frappe.get_meta("Batch", cached=True)
407 searchfields = meta.get_search_fields()
408
409 search_columns = ''
Deepesh Gargf58a5ec2020-10-05 13:55:53 +0530410 search_cond = ''
411
Deepesh Garga0d192e2020-09-22 13:54:07 +0530412 if searchfields:
413 search_columns = ", " + ", ".join(searchfields)
Deepesh Garg1fae7742020-10-05 12:38:54 +0530414 search_cond = " or " + " or ".join([field + " like %(txt)s" for field in searchfields])
Deepesh Garga0d192e2020-09-22 13:54:07 +0530415
Anand Doshi0dc79f42015-04-06 12:59:34 +0530416 if args.get('warehouse'):
Deepesh Garga0d192e2020-09-22 13:54:07 +0530417 searchfields = ['batch.' + field for field in searchfields]
418 if searchfields:
419 search_columns = ", " + ", ".join(searchfields)
Deepesh Garg1fae7742020-10-05 12:38:54 +0530420 search_cond = " or " + " or ".join([field + " like %(txt)s" for field in searchfields])
Deepesh Garga0d192e2020-09-22 13:54:07 +0530421
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530422 batch_nos = frappe.db.sql("""select sle.batch_no, round(sum(sle.actual_qty),2), sle.stock_uom,
423 concat('MFG-',batch.manufacturing_date), concat('EXP-',batch.expiry_date)
Deepesh Garga0d192e2020-09-22 13:54:07 +0530424 {search_columns}
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530425 from `tabStock Ledger Entry` sle
426 INNER JOIN `tabBatch` batch on sle.batch_no = batch.name
427 where
428 batch.disabled = 0
Rohit Waghchaurec14aa452021-07-20 18:19:15 +0530429 and sle.is_cancelled = 0
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530430 and sle.item_code = %(item_code)s
431 and sle.warehouse = %(warehouse)s
432 and (sle.batch_no like %(txt)s
Sun Howwrongbum088be372019-12-24 12:29:25 +0530433 or batch.expiry_date like %(txt)s
Deepesh Gargf58a5ec2020-10-05 13:55:53 +0530434 or batch.manufacturing_date like %(txt)s
435 {search_cond})
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530436 and batch.docstatus < 2
437 {cond}
438 {match_conditions}
439 group by batch_no {having_clause}
440 order by batch.expiry_date, sle.batch_no desc
441 limit %(start)s, %(page_len)s""".format(
Deepesh Garga0d192e2020-09-22 13:54:07 +0530442 search_columns = search_columns,
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530443 cond=cond,
444 match_conditions=get_match_cond(doctype),
Deepesh Garg1fae7742020-10-05 12:38:54 +0530445 having_clause = having_clause,
446 search_cond = search_cond
Rohit Waghchaured8ddd1e2019-10-22 14:03:27 +0530447 ), args)
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530448
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530449 return batch_nos
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530450 else:
Deepesh Garga0d192e2020-09-22 13:54:07 +0530451 return frappe.db.sql("""select name, concat('MFG-', manufacturing_date), concat('EXP-',expiry_date)
452 {search_columns}
453 from `tabBatch` batch
Doridel Cahanap59e4c322018-08-06 17:15:18 +0800454 where batch.disabled = 0
455 and item = %(item_code)s
sivankar621740e2018-02-12 14:33:40 +0530456 and (name like %(txt)s
Sun Howwrongbum088be372019-12-24 12:29:25 +0530457 or expiry_date like %(txt)s
Deepesh Gargf58a5ec2020-10-05 13:55:53 +0530458 or manufacturing_date like %(txt)s
459 {search_cond})
Nabin Hait2ed71ba2015-03-20 15:06:30 +0530460 and docstatus < 2
Neil Trini Lasradoebb60f52015-07-08 14:36:09 +0530461 {0}
Anand Doshi0dc79f42015-04-06 12:59:34 +0530462 {match_conditions}
Deepesh Gargf58a5ec2020-10-05 13:55:53 +0530463
Anand Doshi0dc79f42015-04-06 12:59:34 +0530464 order by expiry_date, name desc
Deepesh Garg1fae7742020-10-05 12:38:54 +0530465 limit %(start)s, %(page_len)s""".format(cond, search_columns = search_columns,
466 search_cond = search_cond, match_conditions=get_match_cond(doctype)), args)
Nabin Haitea4aa042014-05-28 12:56:28 +0530467
Himanshud94a38e2020-05-18 14:26:26 +0530468
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530469@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530470@frappe.validate_and_sanitize_search_inputs
Nabin Haitea4aa042014-05-28 12:56:28 +0530471def get_account_list(doctype, txt, searchfield, start, page_len, filters):
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530472 filter_list = []
Nabin Haitea4aa042014-05-28 12:56:28 +0530473
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530474 if isinstance(filters, dict):
475 for key, val in filters.items():
476 if isinstance(val, (list, tuple)):
477 filter_list.append([doctype, key, val[0], val[1]])
478 else:
479 filter_list.append([doctype, key, "=", val])
bhupeshg2e2e973f2015-04-14 22:15:24 +0530480 elif isinstance(filters, list):
481 filter_list.extend(filters)
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530482
Rushabh Mehta38c6b522015-04-23 13:14:17 +0530483 if "is_group" not in [d[1] for d in filter_list]:
484 filter_list.append(["Account", "is_group", "=", "0"])
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530485
486 if searchfield and txt:
487 filter_list.append([doctype, searchfield, "like", "%%%s%%" % txt])
488
Rushabh Mehtac0bb4532014-09-09 16:15:35 +0530489 return frappe.desk.reportview.execute("Account", filters = filter_list,
Nabin Haitea4aa042014-05-28 12:56:28 +0530490 fields = ["name", "parent_account"],
491 limit_start=start, limit_page_length=page_len, as_list=True)
Anand Doshifaefeaa2014-06-24 18:53:04 +0530492
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530493@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530494@frappe.validate_and_sanitize_search_inputs
Marica299e2172020-04-28 13:00:04 +0530495def get_blanket_orders(doctype, txt, searchfield, start, page_len, filters):
496 return frappe.db.sql("""select distinct bo.name, bo.blanket_order_type, bo.to_date
497 from `tabBlanket Order` bo, `tabBlanket Order Item` boi
498 where
499 boi.parent = bo.name
500 and boi.item_code = {item_code}
501 and bo.blanket_order_type = '{blanket_order_type}'
502 and bo.company = {company}
503 and bo.docstatus = 1"""
504 .format(item_code = frappe.db.escape(filters.get("item")),
505 blanket_order_type = filters.get("blanket_order_type"),
506 company = frappe.db.escape(filters.get("company"))
507 ))
Nabin Haitafd14f62015-10-19 11:55:28 +0530508
Himanshud94a38e2020-05-18 14:26:26 +0530509
Nabin Haitafd14f62015-10-19 11:55:28 +0530510@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530511@frappe.validate_and_sanitize_search_inputs
Nabin Haitafd14f62015-10-19 11:55:28 +0530512def get_income_account(doctype, txt, searchfield, start, page_len, filters):
513 from erpnext.controllers.queries import get_match_cond
514
515 # income account can be any Credit account,
516 # but can also be a Asset account with account_type='Income Account' in special circumstances.
517 # Hence the first condition is an "OR"
518 if not filters: filters = {}
519
Anand Doshi21e09a22015-10-29 12:21:41 +0530520 condition = ""
Nabin Haitafd14f62015-10-19 11:55:28 +0530521 if filters.get("company"):
522 condition += "and tabAccount.company = %(company)s"
Anand Doshi21e09a22015-10-29 12:21:41 +0530523
Nabin Haitafd14f62015-10-19 11:55:28 +0530524 return frappe.db.sql("""select tabAccount.name from `tabAccount`
525 where (tabAccount.report_type = "Profit and Loss"
526 or tabAccount.account_type in ("Income Account", "Temporary"))
527 and tabAccount.is_group=0
528 and tabAccount.`{key}` LIKE %(txt)s
Rushabh Mehta3574b372016-03-11 14:33:04 +0530529 {condition} {match_condition}
530 order by idx desc, name"""
Nabin Haitafd14f62015-10-19 11:55:28 +0530531 .format(condition=condition, match_condition=get_match_cond(doctype), key=searchfield), {
Suraj Shetty4b404c42018-09-27 15:39:34 +0530532 'txt': '%' + txt + '%',
Nabin Haitafd14f62015-10-19 11:55:28 +0530533 'company': filters.get("company", "")
Anand Doshi21e09a22015-10-29 12:21:41 +0530534 })
Nabin Hait3a15c922016-03-04 12:30:46 +0530535
Deepesh Garg96e874b2020-11-15 22:43:01 +0530536@frappe.whitelist()
537@frappe.validate_and_sanitize_search_inputs
538def get_filtered_dimensions(doctype, txt, searchfield, start, page_len, filters):
Chillar Anand915b3432021-09-02 16:44:59 +0530539 from erpnext.accounts.doctype.accounting_dimension_filter.accounting_dimension_filter import (
540 get_dimension_filter_map,
541 )
Deepesh Garg96e874b2020-11-15 22:43:01 +0530542 dimension_filters = get_dimension_filter_map()
543 dimension_filters = dimension_filters.get((filters.get('dimension'),filters.get('account')))
Deepesh Garg6c17b842020-11-25 13:42:16 +0530544 query_filters = []
mergify[bot]071118f2021-11-30 13:15:20 +0000545 or_filters = []
546 fields = ['name']
547
548 searchfields = frappe.get_meta(doctype).get_search_fields()
Deepesh Garg96e874b2020-11-15 22:43:01 +0530549
550 meta = frappe.get_meta(doctype)
Deepesh Garg96e874b2020-11-15 22:43:01 +0530551 if meta.is_tree:
Deepesh Garg6c17b842020-11-25 13:42:16 +0530552 query_filters.append(['is_group', '=', 0])
Deepesh Garg96e874b2020-11-15 22:43:01 +0530553
Subin Tom333e44e2021-08-18 16:17:54 +0530554 if meta.has_field('disabled'):
555 query_filters.append(['disabled', '!=', 1])
556
Deepesh Garg96e874b2020-11-15 22:43:01 +0530557 if meta.has_field('company'):
Deepesh Garg6c17b842020-11-25 13:42:16 +0530558 query_filters.append(['company', '=', filters.get('company')])
559
mergify[bot]071118f2021-11-30 13:15:20 +0000560 for field in searchfields:
561 or_filters.append([field, 'LIKE', "%%%s%%" % txt])
562 fields.append(field)
Deepesh Garg96e874b2020-11-15 22:43:01 +0530563
564 if dimension_filters:
565 if dimension_filters['allow_or_restrict'] == 'Allow':
566 query_selector = 'in'
567 else:
568 query_selector = 'not in'
569
570 if len(dimension_filters['allowed_dimensions']) == 1:
571 dimensions = tuple(dimension_filters['allowed_dimensions'] * 2)
572 else:
573 dimensions = tuple(dimension_filters['allowed_dimensions'])
574
Deepesh Garg6c17b842020-11-25 13:42:16 +0530575 query_filters.append(['name', query_selector, dimensions])
Deepesh Garg96e874b2020-11-15 22:43:01 +0530576
mergify[bot]071118f2021-11-30 13:15:20 +0000577 output = frappe.get_list(doctype, fields=fields, filters=query_filters, or_filters=or_filters, as_list=1)
Deepesh Garg6c17b842020-11-25 13:42:16 +0530578
mergify[bot]071118f2021-11-30 13:15:20 +0000579 return [tuple(d) for d in set(output)]
Nabin Hait3a15c922016-03-04 12:30:46 +0530580
581@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530582@frappe.validate_and_sanitize_search_inputs
Nabin Hait3a15c922016-03-04 12:30:46 +0530583def get_expense_account(doctype, txt, searchfield, start, page_len, filters):
584 from erpnext.controllers.queries import get_match_cond
Rushabh Mehta203cc962016-04-07 15:25:43 +0530585
Nabin Hait3a15c922016-03-04 12:30:46 +0530586 if not filters: filters = {}
587
588 condition = ""
589 if filters.get("company"):
590 condition += "and tabAccount.company = %(company)s"
Rushabh Mehta203cc962016-04-07 15:25:43 +0530591
Nabin Hait3a15c922016-03-04 12:30:46 +0530592 return frappe.db.sql("""select tabAccount.name from `tabAccount`
593 where (tabAccount.report_type = "Profit and Loss"
Mangesh-Khairnar5619db22019-08-21 14:49:24 +0530594 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 +0530595 and tabAccount.is_group=0
596 and tabAccount.docstatus!=2
597 and tabAccount.{key} LIKE %(txt)s
598 {condition} {match_condition}"""
Suraj Shettybfc195d2018-09-21 10:20:52 +0530599 .format(condition=condition, key=searchfield,
Nabin Hait3a15c922016-03-04 12:30:46 +0530600 match_condition=get_match_cond(doctype)), {
Neil Trini Lasrado30b97b02016-03-31 23:10:13 +0530601 'company': filters.get("company", ""),
Suraj Shetty4b404c42018-09-27 15:39:34 +0530602 'txt': '%' + txt + '%'
Maxwell Morais35572612016-07-21 23:42:59 -0300603 })
suyashphadtare049a88c2017-01-12 17:49:37 +0530604
605
606@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530607@frappe.validate_and_sanitize_search_inputs
suyashphadtare049a88c2017-01-12 17:49:37 +0530608def warehouse_query(doctype, txt, searchfield, start, page_len, filters):
609 # Should be used when item code is passed in filters.
suyashphadtare750a0672017-01-18 15:35:01 +0530610 conditions, bin_conditions = [], []
611 filter_dict = get_doctype_wise_filters(filters)
612
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530613 query = """select `tabWarehouse`.name,
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530614 CONCAT_WS(" : ", "Actual Qty", ifnull(round(`tabBin`.actual_qty, 2), 0 )) actual_qty
615 from `tabWarehouse` left join `tabBin`
616 on `tabBin`.warehouse = `tabWarehouse`.name {bin_conditions}
suyashphadtare34ab1362017-01-31 15:14:44 +0530617 where
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530618 `tabWarehouse`.`{key}` like {txt}
suyashphadtare34ab1362017-01-31 15:14:44 +0530619 {fcond} {mcond}
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530620 order by ifnull(`tabBin`.actual_qty, 0) desc
suyashphadtare34ab1362017-01-31 15:14:44 +0530621 limit
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530622 {start}, {page_len}
suyashphadtare34ab1362017-01-31 15:14:44 +0530623 """.format(
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530624 bin_conditions=get_filters_cond(doctype, filter_dict.get("Bin"),bin_conditions, ignore_permissions=True),
Suraj Shettybfc195d2018-09-21 10:20:52 +0530625 key=searchfield,
suyashphadtare34ab1362017-01-31 15:14:44 +0530626 fcond=get_filters_cond(doctype, filter_dict.get("Warehouse"), conditions),
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530627 mcond=get_match_cond(doctype),
628 start=start,
629 page_len=page_len,
630 txt=frappe.db.escape('%{0}%'.format(txt))
631 )
632
633 return frappe.db.sql(query)
suyashphadtare750a0672017-01-18 15:35:01 +0530634
635
636def get_doctype_wise_filters(filters):
637 # Helper function to seperate filters doctype_wise
638 filter_dict = defaultdict(list)
639 for row in filters:
640 filter_dict[row[0]].append(row)
641 return filter_dict
tundebabzy2a4fefc2017-11-29 06:23:09 +0100642
643
644@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530645@frappe.validate_and_sanitize_search_inputs
tundebabzy2a4fefc2017-11-29 06:23:09 +0100646def get_batch_numbers(doctype, txt, searchfield, start, page_len, filters):
rohitwaghchaure9fbed562018-01-12 16:22:33 +0530647 query = """select batch_id from `tabBatch`
Doridel Cahanap59e4c322018-08-06 17:15:18 +0800648 where disabled = 0
649 and (expiry_date >= CURDATE() or expiry_date IS NULL)
Suraj Shettybfc195d2018-09-21 10:20:52 +0530650 and name like {txt}""".format(txt = frappe.db.escape('%{0}%'.format(txt)))
tundebabzy2a4fefc2017-11-29 06:23:09 +0100651
rohitwaghchaure9fbed562018-01-12 16:22:33 +0530652 if filters and filters.get('item'):
Suraj Shettybfc195d2018-09-21 10:20:52 +0530653 query += " and item = {item}".format(item = frappe.db.escape(filters.get('item')))
tundebabzy2a4fefc2017-11-29 06:23:09 +0100654
Sachin Mane64f48db2018-01-08 17:57:32 +0530655 return frappe.db.sql(query, filters)
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530656
Himanshud94a38e2020-05-18 14:26:26 +0530657
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530658@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530659@frappe.validate_and_sanitize_search_inputs
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530660def item_manufacturer_query(doctype, txt, searchfield, start, page_len, filters):
Maricabac4b932019-09-16 19:44:28 +0530661 item_filters = [
662 ['manufacturer', 'like', '%' + txt + '%'],
663 ['item_code', '=', filters.get("item_code")]
664 ]
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530665
Maricabac4b932019-09-16 19:44:28 +0530666 item_manufacturers = frappe.get_all(
667 "Item Manufacturer",
668 fields=["manufacturer", "manufacturer_part_no"],
669 filters=item_filters,
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530670 limit_start=start,
671 limit_page_length=page_len,
672 as_list=1
673 )
Maricabac4b932019-09-16 19:44:28 +0530674 return item_manufacturers
Saqibd9956092019-11-18 11:46:55 +0530675
Himanshud94a38e2020-05-18 14:26:26 +0530676
Saqibd9956092019-11-18 11:46:55 +0530677@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530678@frappe.validate_and_sanitize_search_inputs
Saqibd9956092019-11-18 11:46:55 +0530679def get_purchase_receipts(doctype, txt, searchfield, start, page_len, filters):
680 query = """
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530681 select pr.name
Saqibd9956092019-11-18 11:46:55 +0530682 from `tabPurchase Receipt` pr, `tabPurchase Receipt Item` pritem
683 where pr.docstatus = 1 and pritem.parent = pr.name
684 and pr.name like {txt}""".format(txt = frappe.db.escape('%{0}%'.format(txt)))
685
686 if filters and filters.get('item_code'):
687 query += " and pritem.item_code = {item_code}".format(item_code = frappe.db.escape(filters.get('item_code')))
688
689 return frappe.db.sql(query, filters)
690
Himanshud94a38e2020-05-18 14:26:26 +0530691
Saqibd9956092019-11-18 11:46:55 +0530692@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530693@frappe.validate_and_sanitize_search_inputs
Saqibd9956092019-11-18 11:46:55 +0530694def get_purchase_invoices(doctype, txt, searchfield, start, page_len, filters):
695 query = """
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530696 select pi.name
Saqibd9956092019-11-18 11:46:55 +0530697 from `tabPurchase Invoice` pi, `tabPurchase Invoice Item` piitem
698 where pi.docstatus = 1 and piitem.parent = pi.name
699 and pi.name like {txt}""".format(txt = frappe.db.escape('%{0}%'.format(txt)))
700
701 if filters and filters.get('item_code'):
702 query += " and piitem.item_code = {item_code}".format(item_code = frappe.db.escape(filters.get('item_code')))
703
704 return frappe.db.sql(query, filters)
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530705
Himanshud94a38e2020-05-18 14:26:26 +0530706
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530707@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530708@frappe.validate_and_sanitize_search_inputs
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530709def get_tax_template(doctype, txt, searchfield, start, page_len, filters):
710
711 item_doc = frappe.get_cached_doc('Item', filters.get('item_code'))
712 item_group = filters.get('item_group')
barredterraf60e0402022-01-18 21:15:27 +0100713 company = filters.get('company')
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530714 taxes = item_doc.taxes or []
715
716 while item_group:
717 item_group_doc = frappe.get_cached_doc('Item Group', item_group)
718 taxes += item_group_doc.taxes or []
719 item_group = item_group_doc.parent_item_group
720
721 if not taxes:
barredterraf60e0402022-01-18 21:15:27 +0100722 return frappe.get_all('Item Tax Template', filters={'disabled': 0, 'company': company}, as_list=True)
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530723 else:
Marica0fcb05a2020-08-10 14:48:13 +0530724 valid_from = filters.get('valid_from')
725 valid_from = valid_from[1] if isinstance(valid_from, list) else valid_from
726
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530727 args = {
728 'item_code': filters.get('item_code'),
Marica0fcb05a2020-08-10 14:48:13 +0530729 'posting_date': valid_from,
mohammadahmad199041c0c9f2020-06-18 11:18:44 +0500730 'tax_category': filters.get('tax_category'),
barredterraf60e0402022-01-18 21:15:27 +0100731 'company': company
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530732 }
733
734 taxes = _get_item_tax_template(args, taxes, for_validate=True)
735 return [(d,) for d in set(taxes)]
Himanshud94a38e2020-05-18 14:26:26 +0530736
737
Ankush Menat7eac4a22021-04-19 10:33:39 +0530738def get_fields(doctype, fields=None):
739 if fields is None:
740 fields = []
Himanshud94a38e2020-05-18 14:26:26 +0530741 meta = frappe.get_meta(doctype)
742 fields.extend(meta.get_search_fields())
743
744 if meta.title_field and not meta.title_field.strip() in fields:
745 fields.insert(1, meta.title_field.strip())
746
747 return unique(fields)