blob: 0de75d453ee030bc987867f11b18935ab331d8d5 [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
Rohit Waghchaureacd12c52023-06-04 16:09:01 +05306from collections import OrderedDict, defaultdict
Chillar Anand915b3432021-09-02 16:44:59 +05307
8import frappe
ruthra kumar4eefb442024-01-16 13:38:53 +05309from frappe import qb, scrub
Chillar Anand915b3432021-09-02 16:44:59 +053010from frappe.desk.reportview import get_filters_cond, get_match_cond
ruthra kumarbfe42fd2024-01-16 14:35:06 +053011from frappe.query_builder import Criterion, CustomFunction
12from frappe.query_builder.functions import Concat, Locate, Sum
Rohit Waghchaureacd12c52023-06-04 16:09:01 +053013from frappe.utils import nowdate, today, unique
ruthra kumarbfe42fd2024-01-16 14:35:06 +053014from pypika import Order
Chillar Anand915b3432021-09-02 16:44:59 +053015
16import erpnext
Deepesh Gargef0d26c2020-01-06 15:34:15 +053017from erpnext.stock.get_item_details import _get_item_tax_template
Chillar Anand915b3432021-09-02 16:44:59 +053018
Saurabh02875592013-07-08 18:45:55 +053019
Chinmay D. Paiaa121092020-07-01 21:14:32 +053020# searches for active employees
21@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +053022@frappe.validate_and_sanitize_search_inputs
Saurabh02875592013-07-08 18:45:55 +053023def employee_query(doctype, txt, searchfield, start, page_len, filters):
Sagar Vora9baa2222022-08-03 05:42:30 +000024 doctype = "Employee"
Kanchan Chauhan7652b852016-11-16 15:29:01 +053025 conditions = []
Sagar Vora9baa2222022-08-03 05:42:30 +000026 fields = get_fields(doctype, ["name", "employee_name"])
Himanshud94a38e2020-05-18 14:26:26 +053027
Ankush Menat494bd9e2022-03-28 18:52:46 +053028 return frappe.db.sql(
29 """select {fields} from `tabEmployee`
Anurag Mishrafc98abe2021-06-23 11:21:38 +053030 where status in ('Active', 'Suspended')
Anand Doshibd67e872014-04-11 16:51:27 +053031 and docstatus < 2
Anand Doshi48d3b542014-07-09 13:15:03 +053032 and ({key} like %(txt)s
33 or employee_name like %(txt)s)
Kanchan Chauhan7652b852016-11-16 15:29:01 +053034 {fcond} {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +053035 order by
Conorea28ed12022-06-17 10:47:48 -050036 (case when locate(%(_txt)s, name) > 0 then locate(%(_txt)s, name) else 99999 end),
37 (case when locate(%(_txt)s, employee_name) > 0 then locate(%(_txt)s, employee_name) else 99999 end),
Rushabh Mehta3574b372016-03-11 14:33:04 +053038 idx desc,
Anand Doshi652bc072014-04-16 15:21:46 +053039 name, employee_name
Conor00ef4992022-06-14 00:19:07 -050040 limit %(page_len)s offset %(start)s""".format(
Ankush Menat494bd9e2022-03-28 18:52:46 +053041 **{
42 "fields": ", ".join(fields),
43 "key": searchfield,
44 "fcond": get_filters_cond(doctype, filters, conditions),
45 "mcond": get_match_cond(doctype),
46 }
47 ),
48 {"txt": "%%%s%%" % txt, "_txt": txt.replace("%", ""), "start": start, "page_len": page_len},
49 )
Saurabh02875592013-07-08 18:45:55 +053050
Himanshud94a38e2020-05-18 14:26:26 +053051
52# searches for leads which are not converted
Chinmay D. Paiaa121092020-07-01 21:14:32 +053053@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +053054@frappe.validate_and_sanitize_search_inputs
Anand Doshibd67e872014-04-11 16:51:27 +053055def lead_query(doctype, txt, searchfield, start, page_len, filters):
Sagar Vora9baa2222022-08-03 05:42:30 +000056 doctype = "Lead"
57 fields = get_fields(doctype, ["name", "lead_name", "company_name"])
Himanshud94a38e2020-05-18 14:26:26 +053058
HarryPauloe12e3bb2023-05-13 23:38:47 -030059 searchfields = frappe.get_meta(doctype).get_search_fields()
60 searchfields = " or ".join(field + " like %(txt)s" for field in searchfields)
61
Ankush Menat494bd9e2022-03-28 18:52:46 +053062 return frappe.db.sql(
63 """select {fields} from `tabLead`
Anand Doshibd67e872014-04-11 16:51:27 +053064 where docstatus < 2
65 and ifnull(status, '') != 'Converted'
Anand Doshi48d3b542014-07-09 13:15:03 +053066 and ({key} like %(txt)s
67 or lead_name like %(txt)s
HarryPauloe12e3bb2023-05-13 23:38:47 -030068 or company_name like %(txt)s
69 or {scond})
Anand Doshi48d3b542014-07-09 13:15:03 +053070 {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +053071 order by
Conorea28ed12022-06-17 10:47:48 -050072 (case when locate(%(_txt)s, name) > 0 then locate(%(_txt)s, name) else 99999 end),
73 (case when locate(%(_txt)s, lead_name) > 0 then locate(%(_txt)s, lead_name) else 99999 end),
74 (case when locate(%(_txt)s, company_name) > 0 then locate(%(_txt)s, company_name) else 99999 end),
Rushabh Mehta3574b372016-03-11 14:33:04 +053075 idx desc,
Anand Doshi652bc072014-04-16 15:21:46 +053076 name, lead_name
Conor00ef4992022-06-14 00:19:07 -050077 limit %(page_len)s offset %(start)s""".format(
HarryPauloe12e3bb2023-05-13 23:38:47 -030078 **{
79 "fields": ", ".join(fields),
80 "key": searchfield,
81 "scond": searchfields,
82 "mcond": get_match_cond(doctype),
83 }
Ankush Menat494bd9e2022-03-28 18:52:46 +053084 ),
85 {"txt": "%%%s%%" % txt, "_txt": txt.replace("%", ""), "start": start, "page_len": page_len},
86 )
87
Himanshud94a38e2020-05-18 14:26:26 +053088
Chinmay D. Paiaa121092020-07-01 21:14:32 +053089@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +053090@frappe.validate_and_sanitize_search_inputs
Nabin Hait9a380ef2013-07-16 17:24:17 +053091def tax_account_query(doctype, txt, searchfield, start, page_len, filters):
Sagar Vora9baa2222022-08-03 05:42:30 +000092 doctype = "Account"
Ankush Menat494bd9e2022-03-28 18:52:46 +053093 company_currency = erpnext.get_company_currency(filters.get("company"))
Deepesh Gargfbf6e562020-03-31 10:45:32 +053094
Suraj Shetty1923ef02020-08-05 19:42:25 +053095 def get_accounts(with_account_type_filter):
Ankush Menat494bd9e2022-03-28 18:52:46 +053096 account_type_condition = ""
Suraj Shetty1923ef02020-08-05 19:42:25 +053097 if with_account_type_filter:
98 account_type_condition = "AND account_type in %(account_types)s"
99
Ankush Menat494bd9e2022-03-28 18:52:46 +0530100 accounts = frappe.db.sql(
101 """
Suraj Shetty1923ef02020-08-05 19:42:25 +0530102 SELECT name, parent_account
103 FROM `tabAccount`
104 WHERE `tabAccount`.docstatus!=2
105 {account_type_condition}
106 AND is_group = 0
107 AND company = %(company)s
Saqib Ansaria1e3ae82022-05-11 13:01:06 +0530108 AND disabled = %(disabled)s
Deepesh Garg57924592022-03-22 18:26:58 +0530109 AND (account_currency = %(currency)s or ifnull(account_currency, '') = '')
Suraj Shetty1923ef02020-08-05 19:42:25 +0530110 AND `{searchfield}` LIKE %(txt)s
prssannade7a2bc2020-09-21 13:57:04 +0530111 {mcond}
Suraj Shetty1923ef02020-08-05 19:42:25 +0530112 ORDER BY idx DESC, name
Conor00ef4992022-06-14 00:19:07 -0500113 LIMIT %(limit)s offset %(offset)s
prssannade7a2bc2020-09-21 13:57:04 +0530114 """.format(
115 account_type_condition=account_type_condition,
116 searchfield=searchfield,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530117 mcond=get_match_cond(doctype),
prssannade7a2bc2020-09-21 13:57:04 +0530118 ),
Suraj Shetty1923ef02020-08-05 19:42:25 +0530119 dict(
120 account_types=filters.get("account_type"),
121 company=filters.get("company"),
Saqib Ansaria1e3ae82022-05-11 13:01:06 +0530122 disabled=filters.get("disabled", 0),
Suraj Shetty1923ef02020-08-05 19:42:25 +0530123 currency=company_currency,
124 txt="%{}%".format(txt),
125 offset=start,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530126 limit=page_len,
127 ),
Suraj Shetty1923ef02020-08-05 19:42:25 +0530128 )
129
130 return accounts
131
132 tax_accounts = get_accounts(True)
133
Nabin Hait0c21e2a2014-03-21 11:14:49 +0530134 if not tax_accounts:
Suraj Shetty1923ef02020-08-05 19:42:25 +0530135 tax_accounts = get_accounts(False)
Anand Doshibd67e872014-04-11 16:51:27 +0530136
Nabin Hait0c21e2a2014-03-21 11:14:49 +0530137 return tax_accounts
Saurabh02875592013-07-08 18:45:55 +0530138
Himanshud94a38e2020-05-18 14:26:26 +0530139
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530140@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530141@frappe.validate_and_sanitize_search_inputs
Rushabh Mehta203cc962016-04-07 15:25:43 +0530142def item_query(doctype, txt, searchfield, start, page_len, filters, as_dict=False):
Sagar Vora9baa2222022-08-03 05:42:30 +0000143 doctype = "Item"
Saurabh02875592013-07-08 18:45:55 +0530144 conditions = []
Saurabhf52dc072013-07-10 13:07:49 +0530145
rohitwaghchaurec59371a2021-06-03 20:02:58 +0530146 if isinstance(filters, str):
147 filters = json.loads(filters)
148
Ankush Menat494bd9e2022-03-28 18:52:46 +0530149 # Get searchfields from meta and use in Item Link field query
Sagar Vora9baa2222022-08-03 05:42:30 +0000150 meta = frappe.get_meta(doctype, cached=True)
marination3dbef9d2019-10-28 15:48:10 +0530151 searchfields = meta.get_search_fields()
152
Ankush Menat494bd9e2022-03-28 18:52:46 +0530153 columns = ""
barredterraeb9ee3f2023-12-05 11:22:55 +0100154 extra_searchfields = [field for field in searchfields if field not in ["name", "description"]]
Rohit Waghchaurec42312e2019-11-19 19:05:23 +0530155
156 if extra_searchfields:
Rohit Waghchaurefd889fd2022-09-28 23:00:45 +0530157 columns += ", " + ", ".join(extra_searchfields)
158
159 if "description" in searchfields:
160 columns += """, if(length(tabItem.description) > 40, \
161 concat(substr(tabItem.description, 1, 40), "..."), description) as description"""
marination1e754b12019-10-30 18:33:44 +0530162
Ankush Menat494bd9e2022-03-28 18:52:46 +0530163 searchfields = searchfields + [
164 field
barredterraeb9ee3f2023-12-05 11:22:55 +0100165 for field in [
166 searchfield or "name",
167 "item_code",
168 "item_group",
169 "item_name",
170 ]
171 if field not in searchfields
Ankush Menat494bd9e2022-03-28 18:52:46 +0530172 ]
marination3dbef9d2019-10-28 15:48:10 +0530173 searchfields = " or ".join([field + " like %(txt)s" for field in searchfields])
174
DeeMysterioaa826242021-09-14 13:58:18 +0530175 if filters and isinstance(filters, dict):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530176 if filters.get("customer") or filters.get("supplier"):
177 party = filters.get("customer") or filters.get("supplier")
178 item_rules_list = frappe.get_all(
179 "Party Specific Item", filters={"party": party}, fields=["restrict_based_on", "based_on_value"]
180 )
Rohit Waghchaure721b4132021-06-02 14:13:09 +0530181
DeeMysterioaa826242021-09-14 13:58:18 +0530182 filters_dict = {}
183 for rule in item_rules_list:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530184 if rule["restrict_based_on"] == "Item":
185 rule["restrict_based_on"] = "name"
DeeMysterioaa826242021-09-14 13:58:18 +0530186 filters_dict[rule.restrict_based_on] = []
noahjacobca2fb472021-05-12 16:25:07 +0530187
DeeMysterioaa826242021-09-14 13:58:18 +0530188 for rule in item_rules_list:
189 filters_dict[rule.restrict_based_on].append(rule.based_on_value)
noahjacobca2fb472021-05-12 16:25:07 +0530190
DeeMysterioaa826242021-09-14 13:58:18 +0530191 for filter in filters_dict:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530192 filters[scrub(filter)] = ["in", filters_dict[filter]]
DeeMysterioaa826242021-09-14 13:58:18 +0530193
Ankush Menat494bd9e2022-03-28 18:52:46 +0530194 if filters.get("customer"):
195 del filters["customer"]
DeeMysterioaa826242021-09-14 13:58:18 +0530196 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530197 del filters["supplier"]
Ankush Menat41a95e52022-02-03 13:02:13 +0530198 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530199 filters.pop("customer", None)
200 filters.pop("supplier", None)
DeeMysterioaa826242021-09-14 13:58:18 +0530201
Ankush Menat494bd9e2022-03-28 18:52:46 +0530202 description_cond = ""
Sagar Vora9baa2222022-08-03 05:42:30 +0000203 if frappe.db.count(doctype, cache=True) < 50000:
Rushabh Mehtad5f9ebd2018-04-02 23:37:33 +0530204 # scan description only if items are less than 50000
Ankush Menat494bd9e2022-03-28 18:52:46 +0530205 description_cond = "or tabItem.description LIKE %(txt)s"
Rohit Waghchaurefd889fd2022-09-28 23:00:45 +0530206
Ankush Menat494bd9e2022-03-28 18:52:46 +0530207 return frappe.db.sql(
208 """select
Rohit Waghchaurefd889fd2022-09-28 23:00:45 +0530209 tabItem.name {columns}
Anand Doshibd67e872014-04-11 16:51:27 +0530210 from tabItem
Anand Doshi22c0d782013-11-04 16:23:04 +0530211 where tabItem.docstatus < 2
Anand Doshi21e09a22015-10-29 12:21:41 +0530212 and tabItem.disabled=0
rohitwaghchaure79789072020-05-21 18:10:13 +0530213 and tabItem.has_variants=0
Rushabh Mehta864d1ea2014-06-23 12:20:12 +0530214 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 +0530215 and ({scond} or tabItem.item_code IN (select parent from `tabItem Barcode` where barcode LIKE %(txt)s)
Rohit Waghchaure2bfb0632019-03-02 21:47:55 +0530216 {description_cond})
Anand Doshi22c0d782013-11-04 16:23:04 +0530217 {fcond} {mcond}
Anand Doshi652bc072014-04-16 15:21:46 +0530218 order by
219 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
220 if(locate(%(_txt)s, item_name), locate(%(_txt)s, item_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530221 idx desc,
Anand Doshi652bc072014-04-16 15:21:46 +0530222 name, item_name
Rushabh Mehtabc4e2cd2017-10-17 12:30:34 +0530223 limit %(start)s, %(page_len)s """.format(
marination1e754b12019-10-30 18:33:44 +0530224 columns=columns,
marination3dbef9d2019-10-28 15:48:10 +0530225 scond=searchfields,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530226 fcond=get_filters_cond(doctype, filters, conditions).replace("%", "%%"),
227 mcond=get_match_cond(doctype).replace("%", "%%"),
228 description_cond=description_cond,
229 ),
230 {
231 "today": nowdate(),
232 "txt": "%%%s%%" % txt,
233 "_txt": txt.replace("%", ""),
234 "start": start,
235 "page_len": page_len,
236 },
237 as_dict=as_dict,
238 )
Saurabh02875592013-07-08 18:45:55 +0530239
Himanshud94a38e2020-05-18 14:26:26 +0530240
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530241@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530242@frappe.validate_and_sanitize_search_inputs
Saurabh022ab632017-11-10 15:06:02 +0530243def bom(doctype, txt, searchfield, start, page_len, filters):
Sagar Vora9baa2222022-08-03 05:42:30 +0000244 doctype = "BOM"
Anand Doshibd67e872014-04-11 16:51:27 +0530245 conditions = []
Sagar Vora9baa2222022-08-03 05:42:30 +0000246 fields = get_fields(doctype, ["name", "item"])
Saurabhf52dc072013-07-10 13:07:49 +0530247
Ankush Menat494bd9e2022-03-28 18:52:46 +0530248 return frappe.db.sql(
249 """select {fields}
Conorea28ed12022-06-17 10:47:48 -0500250 from `tabBOM`
251 where `tabBOM`.docstatus=1
252 and `tabBOM`.is_active=1
253 and `tabBOM`.`{key}` like %(txt)s
Nabin Hait62211172016-03-16 16:22:03 +0530254 {fcond} {mcond}
255 order by
Conorea28ed12022-06-17 10:47:48 -0500256 (case when locate(%(_txt)s, name) > 0 then locate(%(_txt)s, name) else 99999 end),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530257 idx desc, name
Conorea28ed12022-06-17 10:47:48 -0500258 limit %(page_len)s offset %(start)s""".format(
Himanshud94a38e2020-05-18 14:26:26 +0530259 fields=", ".join(fields),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530260 fcond=get_filters_cond(doctype, filters, conditions).replace("%", "%%"),
261 mcond=get_match_cond(doctype).replace("%", "%%"),
262 key=searchfield,
263 ),
Mangesh-Khairnar6a796912019-07-08 10:40:40 +0530264 {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530265 "txt": "%" + txt + "%",
266 "_txt": txt.replace("%", ""),
267 "start": start or 0,
268 "page_len": page_len or 20,
269 },
270 )
Saurabh02875592013-07-08 18:45:55 +0530271
Himanshud94a38e2020-05-18 14:26:26 +0530272
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530273@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530274@frappe.validate_and_sanitize_search_inputs
Saurabh02875592013-07-08 18:45:55 +0530275def get_project_name(doctype, txt, searchfield, start, page_len, filters):
ruthra kumar4eefb442024-01-16 13:38:53 +0530276 proj = qb.DocType("Project")
277 qb_filter_and_conditions = []
278 qb_filter_or_conditions = []
ruthra kumarbfe42fd2024-01-16 14:35:06 +0530279 ifelse = CustomFunction("IF", ["condition", "then", "else"])
280
Ankush Menat494bd9e2022-03-28 18:52:46 +0530281 if filters and filters.get("customer"):
Deepesh Gargd0e0b662024-03-07 09:14:56 +0530282 qb_filter_and_conditions.append(
283 (proj.customer == filters.get("customer")) | proj.customer.isnull() | proj.customer == ""
284 )
Anand Doshibd67e872014-04-11 16:51:27 +0530285
ruthra kumar4eefb442024-01-16 13:38:53 +0530286 qb_filter_and_conditions.append(proj.status.notin(["Completed", "Cancelled"]))
Himanshud94a38e2020-05-18 14:26:26 +0530287
ruthra kumar4eefb442024-01-16 13:38:53 +0530288 q = qb.from_(proj)
289
ruthra kumar3349dde2024-01-16 14:28:09 +0530290 fields = get_fields(doctype, ["name", "project_name"])
ruthra kumar4eefb442024-01-16 13:38:53 +0530291 for x in fields:
292 q = q.select(proj[x])
293
ruthra kumarbfe42fd2024-01-16 14:35:06 +0530294 # don't consider 'customer' and 'status' fields for pattern search, as they must be exactly matched
ruthra kumar4eefb442024-01-16 13:38:53 +0530295 searchfields = [
296 x for x in frappe.get_meta(doctype).get_search_fields() if x not in ["customer", "status"]
297 ]
ruthra kumarbfe42fd2024-01-16 14:35:06 +0530298
299 # pattern search
ruthra kumar4eefb442024-01-16 13:38:53 +0530300 if txt:
301 for x in searchfields:
302 qb_filter_or_conditions.append(proj[x].like(f"%{txt}%"))
303
304 q = q.where(Criterion.all(qb_filter_and_conditions)).where(Criterion.any(qb_filter_or_conditions))
ruthra kumarbfe42fd2024-01-16 14:35:06 +0530305
306 # ordering
307 if txt:
308 # project_name containing search string 'txt' will be given higher precedence
309 q = q.orderby(ifelse(Locate(txt, proj.project_name) > 0, Locate(txt, proj.project_name), 99999))
310 q = q.orderby(proj.idx, order=Order.desc).orderby(proj.name)
311
ruthra kumar4eefb442024-01-16 13:38:53 +0530312 if page_len:
313 q = q.limit(page_len)
ruthra kumarbfe42fd2024-01-16 14:35:06 +0530314
315 if start:
316 q = q.offset(start)
ruthra kumar4eefb442024-01-16 13:38:53 +0530317 return q.run()
Anand Doshibd67e872014-04-11 16:51:27 +0530318
tundebabzyf6d738b2017-09-18 12:40:09 +0100319
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530320@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530321@frappe.validate_and_sanitize_search_inputs
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530322def get_delivery_notes_to_be_billed(doctype, txt, searchfield, start, page_len, filters, as_dict):
Sagar Vora9baa2222022-08-03 05:42:30 +0000323 doctype = "Delivery Note"
324 fields = get_fields(doctype, ["name", "customer", "posting_date"])
Himanshud94a38e2020-05-18 14:26:26 +0530325
Ankush Menat494bd9e2022-03-28 18:52:46 +0530326 return frappe.db.sql(
327 """
Himanshud94a38e2020-05-18 14:26:26 +0530328 select %(fields)s
Anand Doshibd67e872014-04-11 16:51:27 +0530329 from `tabDelivery Note`
330 where `tabDelivery Note`.`%(key)s` like %(txt)s and
tundebabzyf6d738b2017-09-18 12:40:09 +0100331 `tabDelivery Note`.docstatus = 1
Conor74a782d2022-06-17 06:31:27 -0500332 and status not in ('Stopped', 'Closed') %(fcond)s
tundebabzyf6d738b2017-09-18 12:40:09 +0100333 and (
334 (`tabDelivery Note`.is_return = 0 and `tabDelivery Note`.per_billed < 100)
Deepesh Garge2dc1022021-04-14 11:21:11 +0530335 or (`tabDelivery Note`.grand_total = 0 and `tabDelivery Note`.per_billed < 100)
tundebabzyf6d738b2017-09-18 12:40:09 +0100336 or (
337 `tabDelivery Note`.is_return = 1
338 and return_against in (select name from `tabDelivery Note` where per_billed < 100)
339 )
340 )
Conor00ef4992022-06-14 00:19:07 -0500341 %(mcond)s order by `tabDelivery Note`.`%(key)s` asc limit %(page_len)s offset %(start)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530342 """
343 % {
344 "fields": ", ".join(["`tabDelivery Note`.{0}".format(f) for f in fields]),
345 "key": searchfield,
346 "fcond": get_filters_cond(doctype, filters, []),
347 "mcond": get_match_cond(doctype),
348 "start": start,
349 "page_len": page_len,
350 "txt": "%(txt)s",
351 },
352 {"txt": ("%%%s%%" % txt)},
353 as_dict=as_dict,
354 )
tundebabzyf6d738b2017-09-18 12:40:09 +0100355
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530356
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530357@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530358@frappe.validate_and_sanitize_search_inputs
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530359def get_batch_no(doctype, txt, searchfield, start, page_len, filters):
Sagar Vora9baa2222022-08-03 05:42:30 +0000360 doctype = "Batch"
Sagar Vora9baa2222022-08-03 05:42:30 +0000361 meta = frappe.get_meta(doctype, cached=True)
Deepesh Garga0d192e2020-09-22 13:54:07 +0530362 searchfields = meta.get_search_fields()
363
Rohit Waghchaure114f2b42024-01-14 23:23:55 +0530364 batches = get_batches_from_stock_ledger_entries(searchfields, txt, filters, start, page_len)
365 batches.extend(
366 get_batches_from_serial_and_batch_bundle(searchfields, txt, filters, start, page_len)
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530367 )
Deepesh Garga0d192e2020-09-22 13:54:07 +0530368
Rohit Waghchaure114f2b42024-01-14 23:23:55 +0530369 filtered_batches = get_filterd_batches(batches)
Deepesh Garga0d192e2020-09-22 13:54:07 +0530370
rohitwaghchaurecef62912024-03-06 19:43:36 +0530371 if filters.get("is_inward"):
372 filtered_batches.extend(get_empty_batches(filters))
373
Rohit Waghchaure114f2b42024-01-14 23:23:55 +0530374 return filtered_batches
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530375
376
rohitwaghchaurecef62912024-03-06 19:43:36 +0530377def get_empty_batches(filters):
378 return frappe.get_all(
379 "Batch",
380 fields=["name", "batch_qty"],
381 filters={"item": filters.get("item_code"), "batch_qty": 0.0},
382 as_list=1,
383 )
384
385
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530386def get_filterd_batches(data):
387 batches = OrderedDict()
388
389 for batch_data in data:
390 if batch_data[0] not in batches:
391 batches[batch_data[0]] = list(batch_data)
392 else:
393 batches[batch_data[0]][1] += batch_data[1]
394
395 filterd_batch = []
396 for batch, batch_data in batches.items():
397 if batch_data[1] > 0:
398 filterd_batch.append(tuple(batch_data))
399
400 return filterd_batch
401
402
Rohit Waghchaure114f2b42024-01-14 23:23:55 +0530403def get_batches_from_stock_ledger_entries(searchfields, txt, filters, start=0, page_len=100):
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530404 stock_ledger_entry = frappe.qb.DocType("Stock Ledger Entry")
405 batch_table = frappe.qb.DocType("Batch")
406
407 expiry_date = filters.get("posting_date") or today()
408
409 query = (
410 frappe.qb.from_(stock_ledger_entry)
411 .inner_join(batch_table)
412 .on(batch_table.name == stock_ledger_entry.batch_no)
413 .select(
414 stock_ledger_entry.batch_no,
415 Sum(stock_ledger_entry.actual_qty).as_("qty"),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530416 )
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530417 .where(((batch_table.expiry_date >= expiry_date) | (batch_table.expiry_date.isnull())))
418 .where(stock_ledger_entry.is_cancelled == 0)
419 .where(
420 (stock_ledger_entry.item_code == filters.get("item_code"))
421 & (batch_table.disabled == 0)
422 & (stock_ledger_entry.batch_no.isnotnull())
Ankush Menat494bd9e2022-03-28 18:52:46 +0530423 )
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530424 .groupby(stock_ledger_entry.batch_no, stock_ledger_entry.warehouse)
Rohit Waghchaure114f2b42024-01-14 23:23:55 +0530425 .offset(start)
426 .limit(page_len)
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530427 )
428
429 query = query.select(
430 Concat("MFG-", batch_table.manufacturing_date).as_("manufacturing_date"),
431 Concat("EXP-", batch_table.expiry_date).as_("expiry_date"),
432 )
433
434 if filters.get("warehouse"):
435 query = query.where(stock_ledger_entry.warehouse == filters.get("warehouse"))
436
437 for field in searchfields:
438 query = query.select(batch_table[field])
439
440 if txt:
Rohit Waghchaure114f2b42024-01-14 23:23:55 +0530441 txt_condition = batch_table.name.like("%{0}%".format(txt))
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530442 for field in searchfields + ["name"]:
Rohit Waghchaure114f2b42024-01-14 23:23:55 +0530443 txt_condition |= batch_table[field].like("%{0}%".format(txt))
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530444
445 query = query.where(txt_condition)
446
Rohit Waghchaure114f2b42024-01-14 23:23:55 +0530447 return query.run(as_list=1) or []
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530448
449
Rohit Waghchaure114f2b42024-01-14 23:23:55 +0530450def get_batches_from_serial_and_batch_bundle(searchfields, txt, filters, start=0, page_len=100):
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530451 bundle = frappe.qb.DocType("Serial and Batch Entry")
452 stock_ledger_entry = frappe.qb.DocType("Stock Ledger Entry")
453 batch_table = frappe.qb.DocType("Batch")
454
455 expiry_date = filters.get("posting_date") or today()
456
457 bundle_query = (
458 frappe.qb.from_(bundle)
459 .inner_join(stock_ledger_entry)
460 .on(bundle.parent == stock_ledger_entry.serial_and_batch_bundle)
461 .inner_join(batch_table)
462 .on(batch_table.name == bundle.batch_no)
463 .select(
464 bundle.batch_no,
465 Sum(bundle.qty).as_("qty"),
466 )
467 .where(((batch_table.expiry_date >= expiry_date) | (batch_table.expiry_date.isnull())))
468 .where(stock_ledger_entry.is_cancelled == 0)
469 .where(
470 (stock_ledger_entry.item_code == filters.get("item_code"))
471 & (batch_table.disabled == 0)
472 & (stock_ledger_entry.serial_and_batch_bundle.isnotnull())
473 )
474 .groupby(bundle.batch_no, bundle.warehouse)
Rohit Waghchaure114f2b42024-01-14 23:23:55 +0530475 .offset(start)
476 .limit(page_len)
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530477 )
478
479 bundle_query = bundle_query.select(
480 Concat("MFG-", batch_table.manufacturing_date),
481 Concat("EXP-", batch_table.expiry_date),
482 )
483
484 if filters.get("warehouse"):
485 bundle_query = bundle_query.where(stock_ledger_entry.warehouse == filters.get("warehouse"))
486
487 for field in searchfields:
488 bundle_query = bundle_query.select(batch_table[field])
489
490 if txt:
Rohit Waghchaure114f2b42024-01-14 23:23:55 +0530491 txt_condition = batch_table.name.like("%{0}%".format(txt))
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530492 for field in searchfields + ["name"]:
Rohit Waghchaure114f2b42024-01-14 23:23:55 +0530493 txt_condition |= batch_table[field].like("%{0}%".format(txt))
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530494
495 bundle_query = bundle_query.where(txt_condition)
496
Rohit Waghchaure114f2b42024-01-14 23:23:55 +0530497 return bundle_query.run(as_list=1)
Nabin Haitea4aa042014-05-28 12:56:28 +0530498
Himanshud94a38e2020-05-18 14:26:26 +0530499
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530500@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530501@frappe.validate_and_sanitize_search_inputs
Nabin Haitea4aa042014-05-28 12:56:28 +0530502def get_account_list(doctype, txt, searchfield, start, page_len, filters):
Sagar Vora9baa2222022-08-03 05:42:30 +0000503 doctype = "Account"
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530504 filter_list = []
Nabin Haitea4aa042014-05-28 12:56:28 +0530505
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530506 if isinstance(filters, dict):
507 for key, val in filters.items():
508 if isinstance(val, (list, tuple)):
509 filter_list.append([doctype, key, val[0], val[1]])
510 else:
511 filter_list.append([doctype, key, "=", val])
bhupeshg2e2e973f2015-04-14 22:15:24 +0530512 elif isinstance(filters, list):
513 filter_list.extend(filters)
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530514
Rushabh Mehta38c6b522015-04-23 13:14:17 +0530515 if "is_group" not in [d[1] for d in filter_list]:
516 filter_list.append(["Account", "is_group", "=", "0"])
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530517
518 if searchfield and txt:
519 filter_list.append([doctype, searchfield, "like", "%%%s%%" % txt])
520
Ankush Menat494bd9e2022-03-28 18:52:46 +0530521 return frappe.desk.reportview.execute(
Sagar Vora9baa2222022-08-03 05:42:30 +0000522 doctype,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530523 filters=filter_list,
524 fields=["name", "parent_account"],
525 limit_start=start,
526 limit_page_length=page_len,
527 as_list=True,
528 )
529
Anand Doshifaefeaa2014-06-24 18:53:04 +0530530
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530531@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530532@frappe.validate_and_sanitize_search_inputs
Marica299e2172020-04-28 13:00:04 +0530533def get_blanket_orders(doctype, txt, searchfield, start, page_len, filters):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530534 return frappe.db.sql(
535 """select distinct bo.name, bo.blanket_order_type, bo.to_date
Marica299e2172020-04-28 13:00:04 +0530536 from `tabBlanket Order` bo, `tabBlanket Order Item` boi
537 where
538 boi.parent = bo.name
539 and boi.item_code = {item_code}
540 and bo.blanket_order_type = '{blanket_order_type}'
541 and bo.company = {company}
Ankush Menat494bd9e2022-03-28 18:52:46 +0530542 and bo.docstatus = 1""".format(
543 item_code=frappe.db.escape(filters.get("item")),
544 blanket_order_type=filters.get("blanket_order_type"),
545 company=frappe.db.escape(filters.get("company")),
546 )
547 )
Nabin Haitafd14f62015-10-19 11:55:28 +0530548
Himanshud94a38e2020-05-18 14:26:26 +0530549
Nabin Haitafd14f62015-10-19 11:55:28 +0530550@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530551@frappe.validate_and_sanitize_search_inputs
Nabin Haitafd14f62015-10-19 11:55:28 +0530552def get_income_account(doctype, txt, searchfield, start, page_len, filters):
553 from erpnext.controllers.queries import get_match_cond
554
555 # income account can be any Credit account,
556 # but can also be a Asset account with account_type='Income Account' in special circumstances.
557 # Hence the first condition is an "OR"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530558 if not filters:
559 filters = {}
Nabin Haitafd14f62015-10-19 11:55:28 +0530560
Sagar Vora9baa2222022-08-03 05:42:30 +0000561 doctype = "Account"
Anand Doshi21e09a22015-10-29 12:21:41 +0530562 condition = ""
Nabin Haitafd14f62015-10-19 11:55:28 +0530563 if filters.get("company"):
564 condition += "and tabAccount.company = %(company)s"
Anand Doshi21e09a22015-10-29 12:21:41 +0530565
ruthra kumar6e3e0942023-11-02 17:19:06 +0530566 condition += f"and tabAccount.disabled = {filters.get('disabled', 0)}"
567
Ankush Menat494bd9e2022-03-28 18:52:46 +0530568 return frappe.db.sql(
569 """select tabAccount.name from `tabAccount`
Nabin Haitafd14f62015-10-19 11:55:28 +0530570 where (tabAccount.report_type = "Profit and Loss"
571 or tabAccount.account_type in ("Income Account", "Temporary"))
572 and tabAccount.is_group=0
573 and tabAccount.`{key}` LIKE %(txt)s
Rushabh Mehta3574b372016-03-11 14:33:04 +0530574 {condition} {match_condition}
Ankush Menat494bd9e2022-03-28 18:52:46 +0530575 order by idx desc, name""".format(
576 condition=condition, match_condition=get_match_cond(doctype), key=searchfield
577 ),
578 {"txt": "%" + txt + "%", "company": filters.get("company", "")},
579 )
580
Nabin Hait3a15c922016-03-04 12:30:46 +0530581
Deepesh Garg96e874b2020-11-15 22:43:01 +0530582@frappe.whitelist()
583@frappe.validate_and_sanitize_search_inputs
Ankush Menat6de71eb2023-04-25 18:33:31 +0530584def get_filtered_dimensions(
585 doctype, txt, searchfield, start, page_len, filters, reference_doctype=None
586):
Chillar Anand915b3432021-09-02 16:44:59 +0530587 from erpnext.accounts.doctype.accounting_dimension_filter.accounting_dimension_filter import (
588 get_dimension_filter_map,
589 )
Ankush Menat494bd9e2022-03-28 18:52:46 +0530590
Deepesh Garg96e874b2020-11-15 22:43:01 +0530591 dimension_filters = get_dimension_filter_map()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530592 dimension_filters = dimension_filters.get((filters.get("dimension"), filters.get("account")))
Deepesh Garg6c17b842020-11-25 13:42:16 +0530593 query_filters = []
mergify[bot]071118f2021-11-30 13:15:20 +0000594 or_filters = []
Ankush Menat494bd9e2022-03-28 18:52:46 +0530595 fields = ["name"]
mergify[bot]071118f2021-11-30 13:15:20 +0000596
597 searchfields = frappe.get_meta(doctype).get_search_fields()
Deepesh Garg96e874b2020-11-15 22:43:01 +0530598
599 meta = frappe.get_meta(doctype)
Rucha Mahabaldaf4ae22024-03-12 20:16:59 +0530600 if meta.is_tree and meta.has_field("is_group"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530601 query_filters.append(["is_group", "=", 0])
Deepesh Garg96e874b2020-11-15 22:43:01 +0530602
Ankush Menat494bd9e2022-03-28 18:52:46 +0530603 if meta.has_field("disabled"):
604 query_filters.append(["disabled", "!=", 1])
Subin Tom333e44e2021-08-18 16:17:54 +0530605
Ankush Menat494bd9e2022-03-28 18:52:46 +0530606 if meta.has_field("company"):
607 query_filters.append(["company", "=", filters.get("company")])
Deepesh Garg6c17b842020-11-25 13:42:16 +0530608
mergify[bot]071118f2021-11-30 13:15:20 +0000609 for field in searchfields:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530610 or_filters.append([field, "LIKE", "%%%s%%" % txt])
mergify[bot]071118f2021-11-30 13:15:20 +0000611 fields.append(field)
Deepesh Garg96e874b2020-11-15 22:43:01 +0530612
613 if dimension_filters:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530614 if dimension_filters["allow_or_restrict"] == "Allow":
615 query_selector = "in"
Deepesh Garg96e874b2020-11-15 22:43:01 +0530616 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530617 query_selector = "not in"
Deepesh Garg96e874b2020-11-15 22:43:01 +0530618
Ankush Menat494bd9e2022-03-28 18:52:46 +0530619 if len(dimension_filters["allowed_dimensions"]) == 1:
620 dimensions = tuple(dimension_filters["allowed_dimensions"] * 2)
Deepesh Garg96e874b2020-11-15 22:43:01 +0530621 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530622 dimensions = tuple(dimension_filters["allowed_dimensions"])
Deepesh Garg96e874b2020-11-15 22:43:01 +0530623
Ankush Menat494bd9e2022-03-28 18:52:46 +0530624 query_filters.append(["name", query_selector, dimensions])
Deepesh Garg96e874b2020-11-15 22:43:01 +0530625
Ankush Menat494bd9e2022-03-28 18:52:46 +0530626 output = frappe.get_list(
Ankush Menat6de71eb2023-04-25 18:33:31 +0530627 doctype,
628 fields=fields,
629 filters=query_filters,
630 or_filters=or_filters,
631 as_list=1,
632 reference_doctype=reference_doctype,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530633 )
Deepesh Garg6c17b842020-11-25 13:42:16 +0530634
mergify[bot]071118f2021-11-30 13:15:20 +0000635 return [tuple(d) for d in set(output)]
Nabin Hait3a15c922016-03-04 12:30:46 +0530636
Ankush Menat494bd9e2022-03-28 18:52:46 +0530637
Nabin Hait3a15c922016-03-04 12:30:46 +0530638@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530639@frappe.validate_and_sanitize_search_inputs
Nabin Hait3a15c922016-03-04 12:30:46 +0530640def get_expense_account(doctype, txt, searchfield, start, page_len, filters):
641 from erpnext.controllers.queries import get_match_cond
Rushabh Mehta203cc962016-04-07 15:25:43 +0530642
Ankush Menat494bd9e2022-03-28 18:52:46 +0530643 if not filters:
644 filters = {}
Nabin Hait3a15c922016-03-04 12:30:46 +0530645
Sagar Vora9baa2222022-08-03 05:42:30 +0000646 doctype = "Account"
Nabin Hait3a15c922016-03-04 12:30:46 +0530647 condition = ""
648 if filters.get("company"):
649 condition += "and tabAccount.company = %(company)s"
Rushabh Mehta203cc962016-04-07 15:25:43 +0530650
Ankush Menat494bd9e2022-03-28 18:52:46 +0530651 return frappe.db.sql(
652 """select tabAccount.name from `tabAccount`
Nabin Hait3a15c922016-03-04 12:30:46 +0530653 where (tabAccount.report_type = "Profit and Loss"
Mangesh-Khairnar5619db22019-08-21 14:49:24 +0530654 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 +0530655 and tabAccount.is_group=0
656 and tabAccount.docstatus!=2
657 and tabAccount.{key} LIKE %(txt)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530658 {condition} {match_condition}""".format(
659 condition=condition, key=searchfield, match_condition=get_match_cond(doctype)
660 ),
661 {"company": filters.get("company", ""), "txt": "%" + txt + "%"},
662 )
suyashphadtare049a88c2017-01-12 17:49:37 +0530663
664
665@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530666@frappe.validate_and_sanitize_search_inputs
suyashphadtare049a88c2017-01-12 17:49:37 +0530667def warehouse_query(doctype, txt, searchfield, start, page_len, filters):
668 # Should be used when item code is passed in filters.
Sagar Vora9baa2222022-08-03 05:42:30 +0000669 doctype = "Warehouse"
suyashphadtare750a0672017-01-18 15:35:01 +0530670 conditions, bin_conditions = [], []
671 filter_dict = get_doctype_wise_filters(filters)
672
s-aga-ree14faa2024-02-05 21:53:25 +0530673 warehouse_field = "name"
674 meta = frappe.get_meta("Warehouse")
675 if meta.get("show_title_field_in_link") and meta.get("title_field"):
676 searchfield = meta.get("title_field")
677 warehouse_field = meta.get("title_field")
678
679 query = """select `tabWarehouse`.`{warehouse_field}`,
Conor74a782d2022-06-17 06:31:27 -0500680 CONCAT_WS(' : ', 'Actual Qty', ifnull(round(`tabBin`.actual_qty, 2), 0 )) actual_qty
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530681 from `tabWarehouse` left join `tabBin`
682 on `tabBin`.warehouse = `tabWarehouse`.name {bin_conditions}
suyashphadtare34ab1362017-01-31 15:14:44 +0530683 where
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530684 `tabWarehouse`.`{key}` like {txt}
suyashphadtare34ab1362017-01-31 15:14:44 +0530685 {fcond} {mcond}
s-aga-ree14faa2024-02-05 21:53:25 +0530686 order by ifnull(`tabBin`.actual_qty, 0) desc, `tabWarehouse`.`{warehouse_field}` asc
suyashphadtare34ab1362017-01-31 15:14:44 +0530687 limit
Conor00ef4992022-06-14 00:19:07 -0500688 {page_len} offset {start}
suyashphadtare34ab1362017-01-31 15:14:44 +0530689 """.format(
s-aga-ree14faa2024-02-05 21:53:25 +0530690 warehouse_field=warehouse_field,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530691 bin_conditions=get_filters_cond(
692 doctype, filter_dict.get("Bin"), bin_conditions, ignore_permissions=True
693 ),
694 key=searchfield,
695 fcond=get_filters_cond(doctype, filter_dict.get("Warehouse"), conditions),
696 mcond=get_match_cond(doctype),
697 start=start,
698 page_len=page_len,
699 txt=frappe.db.escape("%{0}%".format(txt)),
700 )
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530701
702 return frappe.db.sql(query)
suyashphadtare750a0672017-01-18 15:35:01 +0530703
704
705def get_doctype_wise_filters(filters):
706 # Helper function to seperate filters doctype_wise
707 filter_dict = defaultdict(list)
708 for row in filters:
709 filter_dict[row[0]].append(row)
710 return filter_dict
tundebabzy2a4fefc2017-11-29 06:23:09 +0100711
712
713@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530714@frappe.validate_and_sanitize_search_inputs
tundebabzy2a4fefc2017-11-29 06:23:09 +0100715def get_batch_numbers(doctype, txt, searchfield, start, page_len, filters):
rohitwaghchaure9fbed562018-01-12 16:22:33 +0530716 query = """select batch_id from `tabBatch`
Doridel Cahanap59e4c322018-08-06 17:15:18 +0800717 where disabled = 0
Conorb8f728a2022-06-15 01:37:33 -0500718 and (expiry_date >= CURRENT_DATE or expiry_date IS NULL)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530719 and name like {txt}""".format(
720 txt=frappe.db.escape("%{0}%".format(txt))
721 )
tundebabzy2a4fefc2017-11-29 06:23:09 +0100722
Ankush Menat494bd9e2022-03-28 18:52:46 +0530723 if filters and filters.get("item"):
724 query += " and item = {item}".format(item=frappe.db.escape(filters.get("item")))
tundebabzy2a4fefc2017-11-29 06:23:09 +0100725
Sachin Mane64f48db2018-01-08 17:57:32 +0530726 return frappe.db.sql(query, filters)
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530727
Himanshud94a38e2020-05-18 14:26:26 +0530728
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530729@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530730@frappe.validate_and_sanitize_search_inputs
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530731def item_manufacturer_query(doctype, txt, searchfield, start, page_len, filters):
Maricabac4b932019-09-16 19:44:28 +0530732 item_filters = [
Ankush Menat494bd9e2022-03-28 18:52:46 +0530733 ["manufacturer", "like", "%" + txt + "%"],
734 ["item_code", "=", filters.get("item_code")],
Maricabac4b932019-09-16 19:44:28 +0530735 ]
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530736
Maricabac4b932019-09-16 19:44:28 +0530737 item_manufacturers = frappe.get_all(
738 "Item Manufacturer",
739 fields=["manufacturer", "manufacturer_part_no"],
740 filters=item_filters,
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530741 limit_start=start,
742 limit_page_length=page_len,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530743 as_list=1,
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530744 )
Maricabac4b932019-09-16 19:44:28 +0530745 return item_manufacturers
Saqibd9956092019-11-18 11:46:55 +0530746
Himanshud94a38e2020-05-18 14:26:26 +0530747
Saqibd9956092019-11-18 11:46:55 +0530748@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530749@frappe.validate_and_sanitize_search_inputs
Saqibd9956092019-11-18 11:46:55 +0530750def get_purchase_receipts(doctype, txt, searchfield, start, page_len, filters):
751 query = """
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530752 select pr.name
Saqibd9956092019-11-18 11:46:55 +0530753 from `tabPurchase Receipt` pr, `tabPurchase Receipt Item` pritem
754 where pr.docstatus = 1 and pritem.parent = pr.name
Ankush Menat494bd9e2022-03-28 18:52:46 +0530755 and pr.name like {txt}""".format(
756 txt=frappe.db.escape("%{0}%".format(txt))
757 )
Saqibd9956092019-11-18 11:46:55 +0530758
Ankush Menat494bd9e2022-03-28 18:52:46 +0530759 if filters and filters.get("item_code"):
760 query += " and pritem.item_code = {item_code}".format(
761 item_code=frappe.db.escape(filters.get("item_code"))
762 )
Saqibd9956092019-11-18 11:46:55 +0530763
764 return frappe.db.sql(query, filters)
765
Himanshud94a38e2020-05-18 14:26:26 +0530766
Saqibd9956092019-11-18 11:46:55 +0530767@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530768@frappe.validate_and_sanitize_search_inputs
Saqibd9956092019-11-18 11:46:55 +0530769def get_purchase_invoices(doctype, txt, searchfield, start, page_len, filters):
770 query = """
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530771 select pi.name
Saqibd9956092019-11-18 11:46:55 +0530772 from `tabPurchase Invoice` pi, `tabPurchase Invoice Item` piitem
773 where pi.docstatus = 1 and piitem.parent = pi.name
Ankush Menat494bd9e2022-03-28 18:52:46 +0530774 and pi.name like {txt}""".format(
775 txt=frappe.db.escape("%{0}%".format(txt))
776 )
Saqibd9956092019-11-18 11:46:55 +0530777
Ankush Menat494bd9e2022-03-28 18:52:46 +0530778 if filters and filters.get("item_code"):
779 query += " and piitem.item_code = {item_code}".format(
780 item_code=frappe.db.escape(filters.get("item_code"))
781 )
Saqibd9956092019-11-18 11:46:55 +0530782
783 return frappe.db.sql(query, filters)
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530784
Himanshud94a38e2020-05-18 14:26:26 +0530785
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530786@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530787@frappe.validate_and_sanitize_search_inputs
mergify[bot]b4db5e92023-07-18 17:40:49 +0530788def get_doctypes_for_closing(doctype, txt, searchfield, start, page_len, filters):
789 doctypes = frappe.get_hooks("period_closing_doctypes")
790 if txt:
791 doctypes = [d for d in doctypes if txt.lower() in d.lower()]
792 return [(d,) for d in set(doctypes)]
793
794
795@frappe.whitelist()
796@frappe.validate_and_sanitize_search_inputs
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530797def get_tax_template(doctype, txt, searchfield, start, page_len, filters):
798
Ankush Menat494bd9e2022-03-28 18:52:46 +0530799 item_doc = frappe.get_cached_doc("Item", filters.get("item_code"))
800 item_group = filters.get("item_group")
801 company = filters.get("company")
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530802 taxes = item_doc.taxes or []
803
804 while item_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530805 item_group_doc = frappe.get_cached_doc("Item Group", item_group)
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530806 taxes += item_group_doc.taxes or []
807 item_group = item_group_doc.parent_item_group
808
809 if not taxes:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530810 return frappe.get_all(
811 "Item Tax Template", filters={"disabled": 0, "company": company}, as_list=True
812 )
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530813 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530814 valid_from = filters.get("valid_from")
Marica0fcb05a2020-08-10 14:48:13 +0530815 valid_from = valid_from[1] if isinstance(valid_from, list) else valid_from
816
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530817 args = {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530818 "item_code": filters.get("item_code"),
819 "posting_date": valid_from,
820 "tax_category": filters.get("tax_category"),
821 "company": company,
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530822 }
823
824 taxes = _get_item_tax_template(args, taxes, for_validate=True)
825 return [(d,) for d in set(taxes)]
Himanshud94a38e2020-05-18 14:26:26 +0530826
827
Ankush Menat7eac4a22021-04-19 10:33:39 +0530828def get_fields(doctype, fields=None):
829 if fields is None:
830 fields = []
Himanshud94a38e2020-05-18 14:26:26 +0530831 meta = frappe.get_meta(doctype)
832 fields.extend(meta.get_search_fields())
833
barredterraeb9ee3f2023-12-05 11:22:55 +0100834 if meta.title_field and meta.title_field.strip() not in fields:
Himanshud94a38e2020-05-18 14:26:26 +0530835 fields.insert(1, meta.title_field.strip())
836
837 return unique(fields)
ruthra kumar662ccd42023-07-22 11:18:11 +0530838
839
840@frappe.whitelist()
841@frappe.validate_and_sanitize_search_inputs
842def get_payment_terms_for_references(doctype, txt, searchfield, start, page_len, filters) -> list:
843 terms = []
844 if filters:
845 terms = frappe.db.get_all(
846 "Payment Schedule",
847 filters={"parent": filters.get("reference")},
848 fields=["payment_term"],
849 limit=page_len,
850 as_list=1,
851 )
852 return terms
s-aga-r00261092023-12-04 18:00:06 +0530853
854
855@frappe.whitelist()
856@frappe.validate_and_sanitize_search_inputs
857def get_filtered_child_rows(doctype, txt, searchfield, start, page_len, filters) -> list:
858 table = frappe.qb.DocType(doctype)
859 query = (
860 frappe.qb.from_(table)
861 .select(
862 table.name,
863 Concat("#", table.idx, ", ", table.item_code),
864 )
865 .orderby(table.idx)
866 .offset(start)
867 .limit(page_len)
868 )
869
870 if filters:
871 for field, value in filters.items():
872 query = query.where(table[field] == value)
873
874 if txt:
875 txt += "%"
876 query = query.where(
877 ((table.idx.like(txt.replace("#", ""))) | (table.item_code.like(txt))) | (table.name.like(txt))
878 )
879
880 return query.run(as_dict=False)