blob: 129ca7a779025a6e8d8145fb6c4647199a1ec57c [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
88 # searches for customer
Saurabh02875592013-07-08 18:45:55 +053089
Himanshud94a38e2020-05-18 14:26:26 +053090
Chinmay D. Paiaa121092020-07-01 21:14:32 +053091@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +053092@frappe.validate_and_sanitize_search_inputs
Rohit Waghchaure5f849932022-10-24 16:10:47 +053093def customer_query(doctype, txt, searchfield, start, page_len, filters, as_dict=False):
Sagar Vora9baa2222022-08-03 05:42:30 +000094 doctype = "Customer"
KanchanChauhan4b888b92017-07-25 14:03:01 +053095 conditions = []
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053096 cust_master_name = frappe.defaults.get_user_default("cust_master_name")
Saurabhf52dc072013-07-10 13:07:49 +053097
Rohit Waghchaure46d148d2022-10-24 15:48:34 +053098 fields = ["name"]
99 if cust_master_name != "Customer Name":
Rohit Waghchaureb0fc5682022-11-03 11:24:58 +0530100 fields.append("customer_name")
Rushabh Mehtab92087c2017-01-13 18:53:11 +0530101
Sagar Vora9baa2222022-08-03 05:42:30 +0000102 fields = get_fields(doctype, fields)
Sagar Vora9baa2222022-08-03 05:42:30 +0000103 searchfields = frappe.get_meta(doctype).get_search_fields()
Ankush Menata9c84f72021-06-11 16:00:48 +0530104 searchfields = " or ".join(field + " like %(txt)s" for field in searchfields)
Saurabh02875592013-07-08 18:45:55 +0530105
Ankush Menat494bd9e2022-03-28 18:52:46 +0530106 return frappe.db.sql(
107 """select {fields} from `tabCustomer`
Anand Doshibd67e872014-04-11 16:51:27 +0530108 where docstatus < 2
Console Admin86231662017-06-23 20:32:52 +0300109 and ({scond}) and disabled=0
KanchanChauhan4b888b92017-07-25 14:03:01 +0530110 {fcond} {mcond}
Anand Doshibd67e872014-04-11 16:51:27 +0530111 order by
Conorea28ed12022-06-17 10:47:48 -0500112 (case when locate(%(_txt)s, name) > 0 then locate(%(_txt)s, name) else 99999 end),
113 (case when locate(%(_txt)s, customer_name) > 0 then locate(%(_txt)s, customer_name) else 99999 end),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530114 idx desc,
Anand Doshibd67e872014-04-11 16:51:27 +0530115 name, customer_name
Conor00ef4992022-06-14 00:19:07 -0500116 limit %(page_len)s offset %(start)s""".format(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530117 **{
118 "fields": ", ".join(fields),
119 "scond": searchfields,
120 "mcond": get_match_cond(doctype),
121 "fcond": get_filters_cond(doctype, filters, conditions).replace("%", "%%"),
122 }
123 ),
124 {"txt": "%%%s%%" % txt, "_txt": txt.replace("%", ""), "start": start, "page_len": page_len},
Rohit Waghchaure5f849932022-10-24 16:10:47 +0530125 as_dict=as_dict,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530126 )
Saurabh02875592013-07-08 18:45:55 +0530127
Himanshud94a38e2020-05-18 14:26:26 +0530128
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530129@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530130@frappe.validate_and_sanitize_search_inputs
Nabin Hait9a380ef2013-07-16 17:24:17 +0530131def tax_account_query(doctype, txt, searchfield, start, page_len, filters):
Sagar Vora9baa2222022-08-03 05:42:30 +0000132 doctype = "Account"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530133 company_currency = erpnext.get_company_currency(filters.get("company"))
Deepesh Gargfbf6e562020-03-31 10:45:32 +0530134
Suraj Shetty1923ef02020-08-05 19:42:25 +0530135 def get_accounts(with_account_type_filter):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530136 account_type_condition = ""
Suraj Shetty1923ef02020-08-05 19:42:25 +0530137 if with_account_type_filter:
138 account_type_condition = "AND account_type in %(account_types)s"
139
Ankush Menat494bd9e2022-03-28 18:52:46 +0530140 accounts = frappe.db.sql(
141 """
Suraj Shetty1923ef02020-08-05 19:42:25 +0530142 SELECT name, parent_account
143 FROM `tabAccount`
144 WHERE `tabAccount`.docstatus!=2
145 {account_type_condition}
146 AND is_group = 0
147 AND company = %(company)s
Saqib Ansaria1e3ae82022-05-11 13:01:06 +0530148 AND disabled = %(disabled)s
Deepesh Garg57924592022-03-22 18:26:58 +0530149 AND (account_currency = %(currency)s or ifnull(account_currency, '') = '')
Suraj Shetty1923ef02020-08-05 19:42:25 +0530150 AND `{searchfield}` LIKE %(txt)s
prssannade7a2bc2020-09-21 13:57:04 +0530151 {mcond}
Suraj Shetty1923ef02020-08-05 19:42:25 +0530152 ORDER BY idx DESC, name
Conor00ef4992022-06-14 00:19:07 -0500153 LIMIT %(limit)s offset %(offset)s
prssannade7a2bc2020-09-21 13:57:04 +0530154 """.format(
155 account_type_condition=account_type_condition,
156 searchfield=searchfield,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530157 mcond=get_match_cond(doctype),
prssannade7a2bc2020-09-21 13:57:04 +0530158 ),
Suraj Shetty1923ef02020-08-05 19:42:25 +0530159 dict(
160 account_types=filters.get("account_type"),
161 company=filters.get("company"),
Saqib Ansaria1e3ae82022-05-11 13:01:06 +0530162 disabled=filters.get("disabled", 0),
Suraj Shetty1923ef02020-08-05 19:42:25 +0530163 currency=company_currency,
164 txt="%{}%".format(txt),
165 offset=start,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530166 limit=page_len,
167 ),
Suraj Shetty1923ef02020-08-05 19:42:25 +0530168 )
169
170 return accounts
171
172 tax_accounts = get_accounts(True)
173
Nabin Hait0c21e2a2014-03-21 11:14:49 +0530174 if not tax_accounts:
Suraj Shetty1923ef02020-08-05 19:42:25 +0530175 tax_accounts = get_accounts(False)
Anand Doshibd67e872014-04-11 16:51:27 +0530176
Nabin Hait0c21e2a2014-03-21 11:14:49 +0530177 return tax_accounts
Saurabh02875592013-07-08 18:45:55 +0530178
Himanshud94a38e2020-05-18 14:26:26 +0530179
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530180@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530181@frappe.validate_and_sanitize_search_inputs
Rushabh Mehta203cc962016-04-07 15:25:43 +0530182def item_query(doctype, txt, searchfield, start, page_len, filters, as_dict=False):
Sagar Vora9baa2222022-08-03 05:42:30 +0000183 doctype = "Item"
Saurabh02875592013-07-08 18:45:55 +0530184 conditions = []
Saurabhf52dc072013-07-10 13:07:49 +0530185
rohitwaghchaurec59371a2021-06-03 20:02:58 +0530186 if isinstance(filters, str):
187 filters = json.loads(filters)
188
Ankush Menat494bd9e2022-03-28 18:52:46 +0530189 # Get searchfields from meta and use in Item Link field query
Sagar Vora9baa2222022-08-03 05:42:30 +0000190 meta = frappe.get_meta(doctype, cached=True)
marination3dbef9d2019-10-28 15:48:10 +0530191 searchfields = meta.get_search_fields()
192
Ankush Menat494bd9e2022-03-28 18:52:46 +0530193 columns = ""
barredterraeb9ee3f2023-12-05 11:22:55 +0100194 extra_searchfields = [field for field in searchfields if field not in ["name", "description"]]
Rohit Waghchaurec42312e2019-11-19 19:05:23 +0530195
196 if extra_searchfields:
Rohit Waghchaurefd889fd2022-09-28 23:00:45 +0530197 columns += ", " + ", ".join(extra_searchfields)
198
199 if "description" in searchfields:
200 columns += """, if(length(tabItem.description) > 40, \
201 concat(substr(tabItem.description, 1, 40), "..."), description) as description"""
marination1e754b12019-10-30 18:33:44 +0530202
Ankush Menat494bd9e2022-03-28 18:52:46 +0530203 searchfields = searchfields + [
204 field
barredterraeb9ee3f2023-12-05 11:22:55 +0100205 for field in [
206 searchfield or "name",
207 "item_code",
208 "item_group",
209 "item_name",
210 ]
211 if field not in searchfields
Ankush Menat494bd9e2022-03-28 18:52:46 +0530212 ]
marination3dbef9d2019-10-28 15:48:10 +0530213 searchfields = " or ".join([field + " like %(txt)s" for field in searchfields])
214
DeeMysterioaa826242021-09-14 13:58:18 +0530215 if filters and isinstance(filters, dict):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530216 if filters.get("customer") or filters.get("supplier"):
217 party = filters.get("customer") or filters.get("supplier")
218 item_rules_list = frappe.get_all(
219 "Party Specific Item", filters={"party": party}, fields=["restrict_based_on", "based_on_value"]
220 )
Rohit Waghchaure721b4132021-06-02 14:13:09 +0530221
DeeMysterioaa826242021-09-14 13:58:18 +0530222 filters_dict = {}
223 for rule in item_rules_list:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530224 if rule["restrict_based_on"] == "Item":
225 rule["restrict_based_on"] = "name"
DeeMysterioaa826242021-09-14 13:58:18 +0530226 filters_dict[rule.restrict_based_on] = []
noahjacobca2fb472021-05-12 16:25:07 +0530227
DeeMysterioaa826242021-09-14 13:58:18 +0530228 for rule in item_rules_list:
229 filters_dict[rule.restrict_based_on].append(rule.based_on_value)
noahjacobca2fb472021-05-12 16:25:07 +0530230
DeeMysterioaa826242021-09-14 13:58:18 +0530231 for filter in filters_dict:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530232 filters[scrub(filter)] = ["in", filters_dict[filter]]
DeeMysterioaa826242021-09-14 13:58:18 +0530233
Ankush Menat494bd9e2022-03-28 18:52:46 +0530234 if filters.get("customer"):
235 del filters["customer"]
DeeMysterioaa826242021-09-14 13:58:18 +0530236 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530237 del filters["supplier"]
Ankush Menat41a95e52022-02-03 13:02:13 +0530238 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530239 filters.pop("customer", None)
240 filters.pop("supplier", None)
DeeMysterioaa826242021-09-14 13:58:18 +0530241
Ankush Menat494bd9e2022-03-28 18:52:46 +0530242 description_cond = ""
Sagar Vora9baa2222022-08-03 05:42:30 +0000243 if frappe.db.count(doctype, cache=True) < 50000:
Rushabh Mehtad5f9ebd2018-04-02 23:37:33 +0530244 # scan description only if items are less than 50000
Ankush Menat494bd9e2022-03-28 18:52:46 +0530245 description_cond = "or tabItem.description LIKE %(txt)s"
Rohit Waghchaurefd889fd2022-09-28 23:00:45 +0530246
Ankush Menat494bd9e2022-03-28 18:52:46 +0530247 return frappe.db.sql(
248 """select
Rohit Waghchaurefd889fd2022-09-28 23:00:45 +0530249 tabItem.name {columns}
Anand Doshibd67e872014-04-11 16:51:27 +0530250 from tabItem
Anand Doshi22c0d782013-11-04 16:23:04 +0530251 where tabItem.docstatus < 2
Anand Doshi21e09a22015-10-29 12:21:41 +0530252 and tabItem.disabled=0
rohitwaghchaure79789072020-05-21 18:10:13 +0530253 and tabItem.has_variants=0
Rushabh Mehta864d1ea2014-06-23 12:20:12 +0530254 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 +0530255 and ({scond} or tabItem.item_code IN (select parent from `tabItem Barcode` where barcode LIKE %(txt)s)
Rohit Waghchaure2bfb0632019-03-02 21:47:55 +0530256 {description_cond})
Anand Doshi22c0d782013-11-04 16:23:04 +0530257 {fcond} {mcond}
Anand Doshi652bc072014-04-16 15:21:46 +0530258 order by
259 if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
260 if(locate(%(_txt)s, item_name), locate(%(_txt)s, item_name), 99999),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530261 idx desc,
Anand Doshi652bc072014-04-16 15:21:46 +0530262 name, item_name
Rushabh Mehtabc4e2cd2017-10-17 12:30:34 +0530263 limit %(start)s, %(page_len)s """.format(
marination1e754b12019-10-30 18:33:44 +0530264 columns=columns,
marination3dbef9d2019-10-28 15:48:10 +0530265 scond=searchfields,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530266 fcond=get_filters_cond(doctype, filters, conditions).replace("%", "%%"),
267 mcond=get_match_cond(doctype).replace("%", "%%"),
268 description_cond=description_cond,
269 ),
270 {
271 "today": nowdate(),
272 "txt": "%%%s%%" % txt,
273 "_txt": txt.replace("%", ""),
274 "start": start,
275 "page_len": page_len,
276 },
277 as_dict=as_dict,
278 )
Saurabh02875592013-07-08 18:45:55 +0530279
Himanshud94a38e2020-05-18 14:26:26 +0530280
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530281@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530282@frappe.validate_and_sanitize_search_inputs
Saurabh022ab632017-11-10 15:06:02 +0530283def bom(doctype, txt, searchfield, start, page_len, filters):
Sagar Vora9baa2222022-08-03 05:42:30 +0000284 doctype = "BOM"
Anand Doshibd67e872014-04-11 16:51:27 +0530285 conditions = []
Sagar Vora9baa2222022-08-03 05:42:30 +0000286 fields = get_fields(doctype, ["name", "item"])
Saurabhf52dc072013-07-10 13:07:49 +0530287
Ankush Menat494bd9e2022-03-28 18:52:46 +0530288 return frappe.db.sql(
289 """select {fields}
Conorea28ed12022-06-17 10:47:48 -0500290 from `tabBOM`
291 where `tabBOM`.docstatus=1
292 and `tabBOM`.is_active=1
293 and `tabBOM`.`{key}` like %(txt)s
Nabin Hait62211172016-03-16 16:22:03 +0530294 {fcond} {mcond}
295 order by
Conorea28ed12022-06-17 10:47:48 -0500296 (case when locate(%(_txt)s, name) > 0 then locate(%(_txt)s, name) else 99999 end),
Rushabh Mehta3574b372016-03-11 14:33:04 +0530297 idx desc, name
Conorea28ed12022-06-17 10:47:48 -0500298 limit %(page_len)s offset %(start)s""".format(
Himanshud94a38e2020-05-18 14:26:26 +0530299 fields=", ".join(fields),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530300 fcond=get_filters_cond(doctype, filters, conditions).replace("%", "%%"),
301 mcond=get_match_cond(doctype).replace("%", "%%"),
302 key=searchfield,
303 ),
Mangesh-Khairnar6a796912019-07-08 10:40:40 +0530304 {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530305 "txt": "%" + txt + "%",
306 "_txt": txt.replace("%", ""),
307 "start": start or 0,
308 "page_len": page_len or 20,
309 },
310 )
Saurabh02875592013-07-08 18:45:55 +0530311
Himanshud94a38e2020-05-18 14:26:26 +0530312
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530313@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530314@frappe.validate_and_sanitize_search_inputs
Saurabh02875592013-07-08 18:45:55 +0530315def get_project_name(doctype, txt, searchfield, start, page_len, filters):
ruthra kumar4eefb442024-01-16 13:38:53 +0530316 proj = qb.DocType("Project")
317 qb_filter_and_conditions = []
318 qb_filter_or_conditions = []
ruthra kumarbfe42fd2024-01-16 14:35:06 +0530319 ifelse = CustomFunction("IF", ["condition", "then", "else"])
320
Ankush Menat494bd9e2022-03-28 18:52:46 +0530321 if filters and filters.get("customer"):
Deepesh Gargd0e0b662024-03-07 09:14:56 +0530322 qb_filter_and_conditions.append(
323 (proj.customer == filters.get("customer")) | proj.customer.isnull() | proj.customer == ""
324 )
Anand Doshibd67e872014-04-11 16:51:27 +0530325
ruthra kumar4eefb442024-01-16 13:38:53 +0530326 qb_filter_and_conditions.append(proj.status.notin(["Completed", "Cancelled"]))
Himanshud94a38e2020-05-18 14:26:26 +0530327
ruthra kumar4eefb442024-01-16 13:38:53 +0530328 q = qb.from_(proj)
329
ruthra kumar3349dde2024-01-16 14:28:09 +0530330 fields = get_fields(doctype, ["name", "project_name"])
ruthra kumar4eefb442024-01-16 13:38:53 +0530331 for x in fields:
332 q = q.select(proj[x])
333
ruthra kumarbfe42fd2024-01-16 14:35:06 +0530334 # don't consider 'customer' and 'status' fields for pattern search, as they must be exactly matched
ruthra kumar4eefb442024-01-16 13:38:53 +0530335 searchfields = [
336 x for x in frappe.get_meta(doctype).get_search_fields() if x not in ["customer", "status"]
337 ]
ruthra kumarbfe42fd2024-01-16 14:35:06 +0530338
339 # pattern search
ruthra kumar4eefb442024-01-16 13:38:53 +0530340 if txt:
341 for x in searchfields:
342 qb_filter_or_conditions.append(proj[x].like(f"%{txt}%"))
343
344 q = q.where(Criterion.all(qb_filter_and_conditions)).where(Criterion.any(qb_filter_or_conditions))
ruthra kumarbfe42fd2024-01-16 14:35:06 +0530345
346 # ordering
347 if txt:
348 # project_name containing search string 'txt' will be given higher precedence
349 q = q.orderby(ifelse(Locate(txt, proj.project_name) > 0, Locate(txt, proj.project_name), 99999))
350 q = q.orderby(proj.idx, order=Order.desc).orderby(proj.name)
351
ruthra kumar4eefb442024-01-16 13:38:53 +0530352 if page_len:
353 q = q.limit(page_len)
ruthra kumarbfe42fd2024-01-16 14:35:06 +0530354
355 if start:
356 q = q.offset(start)
ruthra kumar4eefb442024-01-16 13:38:53 +0530357 return q.run()
Anand Doshibd67e872014-04-11 16:51:27 +0530358
tundebabzyf6d738b2017-09-18 12:40:09 +0100359
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530360@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530361@frappe.validate_and_sanitize_search_inputs
Nabin Hait1e2d7b32017-05-17 13:52:21 +0530362def get_delivery_notes_to_be_billed(doctype, txt, searchfield, start, page_len, filters, as_dict):
Sagar Vora9baa2222022-08-03 05:42:30 +0000363 doctype = "Delivery Note"
364 fields = get_fields(doctype, ["name", "customer", "posting_date"])
Himanshud94a38e2020-05-18 14:26:26 +0530365
Ankush Menat494bd9e2022-03-28 18:52:46 +0530366 return frappe.db.sql(
367 """
Himanshud94a38e2020-05-18 14:26:26 +0530368 select %(fields)s
Anand Doshibd67e872014-04-11 16:51:27 +0530369 from `tabDelivery Note`
370 where `tabDelivery Note`.`%(key)s` like %(txt)s and
tundebabzyf6d738b2017-09-18 12:40:09 +0100371 `tabDelivery Note`.docstatus = 1
Conor74a782d2022-06-17 06:31:27 -0500372 and status not in ('Stopped', 'Closed') %(fcond)s
tundebabzyf6d738b2017-09-18 12:40:09 +0100373 and (
374 (`tabDelivery Note`.is_return = 0 and `tabDelivery Note`.per_billed < 100)
Deepesh Garge2dc1022021-04-14 11:21:11 +0530375 or (`tabDelivery Note`.grand_total = 0 and `tabDelivery Note`.per_billed < 100)
tundebabzyf6d738b2017-09-18 12:40:09 +0100376 or (
377 `tabDelivery Note`.is_return = 1
378 and return_against in (select name from `tabDelivery Note` where per_billed < 100)
379 )
380 )
Conor00ef4992022-06-14 00:19:07 -0500381 %(mcond)s order by `tabDelivery Note`.`%(key)s` asc limit %(page_len)s offset %(start)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530382 """
383 % {
384 "fields": ", ".join(["`tabDelivery Note`.{0}".format(f) for f in fields]),
385 "key": searchfield,
386 "fcond": get_filters_cond(doctype, filters, []),
387 "mcond": get_match_cond(doctype),
388 "start": start,
389 "page_len": page_len,
390 "txt": "%(txt)s",
391 },
392 {"txt": ("%%%s%%" % txt)},
393 as_dict=as_dict,
394 )
tundebabzyf6d738b2017-09-18 12:40:09 +0100395
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530396
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530397@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530398@frappe.validate_and_sanitize_search_inputs
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530399def get_batch_no(doctype, txt, searchfield, start, page_len, filters):
Sagar Vora9baa2222022-08-03 05:42:30 +0000400 doctype = "Batch"
Sagar Vora9baa2222022-08-03 05:42:30 +0000401 meta = frappe.get_meta(doctype, cached=True)
Deepesh Garga0d192e2020-09-22 13:54:07 +0530402 searchfields = meta.get_search_fields()
403
Rohit Waghchaure114f2b42024-01-14 23:23:55 +0530404 batches = get_batches_from_stock_ledger_entries(searchfields, txt, filters, start, page_len)
405 batches.extend(
406 get_batches_from_serial_and_batch_bundle(searchfields, txt, filters, start, page_len)
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530407 )
Deepesh Garga0d192e2020-09-22 13:54:07 +0530408
Rohit Waghchaure114f2b42024-01-14 23:23:55 +0530409 filtered_batches = get_filterd_batches(batches)
Deepesh Garga0d192e2020-09-22 13:54:07 +0530410
rohitwaghchaurecef62912024-03-06 19:43:36 +0530411 if filters.get("is_inward"):
412 filtered_batches.extend(get_empty_batches(filters))
413
Rohit Waghchaure114f2b42024-01-14 23:23:55 +0530414 return filtered_batches
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530415
416
rohitwaghchaurecef62912024-03-06 19:43:36 +0530417def get_empty_batches(filters):
418 return frappe.get_all(
419 "Batch",
420 fields=["name", "batch_qty"],
421 filters={"item": filters.get("item_code"), "batch_qty": 0.0},
422 as_list=1,
423 )
424
425
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530426def get_filterd_batches(data):
427 batches = OrderedDict()
428
429 for batch_data in data:
430 if batch_data[0] not in batches:
431 batches[batch_data[0]] = list(batch_data)
432 else:
433 batches[batch_data[0]][1] += batch_data[1]
434
435 filterd_batch = []
436 for batch, batch_data in batches.items():
437 if batch_data[1] > 0:
438 filterd_batch.append(tuple(batch_data))
439
440 return filterd_batch
441
442
Rohit Waghchaure114f2b42024-01-14 23:23:55 +0530443def get_batches_from_stock_ledger_entries(searchfields, txt, filters, start=0, page_len=100):
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530444 stock_ledger_entry = frappe.qb.DocType("Stock Ledger Entry")
445 batch_table = frappe.qb.DocType("Batch")
446
447 expiry_date = filters.get("posting_date") or today()
448
449 query = (
450 frappe.qb.from_(stock_ledger_entry)
451 .inner_join(batch_table)
452 .on(batch_table.name == stock_ledger_entry.batch_no)
453 .select(
454 stock_ledger_entry.batch_no,
455 Sum(stock_ledger_entry.actual_qty).as_("qty"),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530456 )
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530457 .where(((batch_table.expiry_date >= expiry_date) | (batch_table.expiry_date.isnull())))
458 .where(stock_ledger_entry.is_cancelled == 0)
459 .where(
460 (stock_ledger_entry.item_code == filters.get("item_code"))
461 & (batch_table.disabled == 0)
462 & (stock_ledger_entry.batch_no.isnotnull())
Ankush Menat494bd9e2022-03-28 18:52:46 +0530463 )
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530464 .groupby(stock_ledger_entry.batch_no, stock_ledger_entry.warehouse)
Rohit Waghchaure114f2b42024-01-14 23:23:55 +0530465 .offset(start)
466 .limit(page_len)
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530467 )
468
469 query = query.select(
470 Concat("MFG-", batch_table.manufacturing_date).as_("manufacturing_date"),
471 Concat("EXP-", batch_table.expiry_date).as_("expiry_date"),
472 )
473
474 if filters.get("warehouse"):
475 query = query.where(stock_ledger_entry.warehouse == filters.get("warehouse"))
476
477 for field in searchfields:
478 query = query.select(batch_table[field])
479
480 if txt:
Rohit Waghchaure114f2b42024-01-14 23:23:55 +0530481 txt_condition = batch_table.name.like("%{0}%".format(txt))
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530482 for field in searchfields + ["name"]:
Rohit Waghchaure114f2b42024-01-14 23:23:55 +0530483 txt_condition |= batch_table[field].like("%{0}%".format(txt))
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530484
485 query = query.where(txt_condition)
486
Rohit Waghchaure114f2b42024-01-14 23:23:55 +0530487 return query.run(as_list=1) or []
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530488
489
Rohit Waghchaure114f2b42024-01-14 23:23:55 +0530490def get_batches_from_serial_and_batch_bundle(searchfields, txt, filters, start=0, page_len=100):
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530491 bundle = frappe.qb.DocType("Serial and Batch Entry")
492 stock_ledger_entry = frappe.qb.DocType("Stock Ledger Entry")
493 batch_table = frappe.qb.DocType("Batch")
494
495 expiry_date = filters.get("posting_date") or today()
496
497 bundle_query = (
498 frappe.qb.from_(bundle)
499 .inner_join(stock_ledger_entry)
500 .on(bundle.parent == stock_ledger_entry.serial_and_batch_bundle)
501 .inner_join(batch_table)
502 .on(batch_table.name == bundle.batch_no)
503 .select(
504 bundle.batch_no,
505 Sum(bundle.qty).as_("qty"),
506 )
507 .where(((batch_table.expiry_date >= expiry_date) | (batch_table.expiry_date.isnull())))
508 .where(stock_ledger_entry.is_cancelled == 0)
509 .where(
510 (stock_ledger_entry.item_code == filters.get("item_code"))
511 & (batch_table.disabled == 0)
512 & (stock_ledger_entry.serial_and_batch_bundle.isnotnull())
513 )
514 .groupby(bundle.batch_no, bundle.warehouse)
Rohit Waghchaure114f2b42024-01-14 23:23:55 +0530515 .offset(start)
516 .limit(page_len)
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530517 )
518
519 bundle_query = bundle_query.select(
520 Concat("MFG-", batch_table.manufacturing_date),
521 Concat("EXP-", batch_table.expiry_date),
522 )
523
524 if filters.get("warehouse"):
525 bundle_query = bundle_query.where(stock_ledger_entry.warehouse == filters.get("warehouse"))
526
527 for field in searchfields:
528 bundle_query = bundle_query.select(batch_table[field])
529
530 if txt:
Rohit Waghchaure114f2b42024-01-14 23:23:55 +0530531 txt_condition = batch_table.name.like("%{0}%".format(txt))
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530532 for field in searchfields + ["name"]:
Rohit Waghchaure114f2b42024-01-14 23:23:55 +0530533 txt_condition |= batch_table[field].like("%{0}%".format(txt))
Rohit Waghchaureacd12c52023-06-04 16:09:01 +0530534
535 bundle_query = bundle_query.where(txt_condition)
536
Rohit Waghchaure114f2b42024-01-14 23:23:55 +0530537 return bundle_query.run(as_list=1)
Nabin Haitea4aa042014-05-28 12:56:28 +0530538
Himanshud94a38e2020-05-18 14:26:26 +0530539
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530540@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530541@frappe.validate_and_sanitize_search_inputs
Nabin Haitea4aa042014-05-28 12:56:28 +0530542def get_account_list(doctype, txt, searchfield, start, page_len, filters):
Sagar Vora9baa2222022-08-03 05:42:30 +0000543 doctype = "Account"
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530544 filter_list = []
Nabin Haitea4aa042014-05-28 12:56:28 +0530545
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530546 if isinstance(filters, dict):
547 for key, val in filters.items():
548 if isinstance(val, (list, tuple)):
549 filter_list.append([doctype, key, val[0], val[1]])
550 else:
551 filter_list.append([doctype, key, "=", val])
bhupeshg2e2e973f2015-04-14 22:15:24 +0530552 elif isinstance(filters, list):
553 filter_list.extend(filters)
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530554
Rushabh Mehta38c6b522015-04-23 13:14:17 +0530555 if "is_group" not in [d[1] for d in filter_list]:
556 filter_list.append(["Account", "is_group", "=", "0"])
Nabin Haite1b2b3e2014-06-14 15:26:10 +0530557
558 if searchfield and txt:
559 filter_list.append([doctype, searchfield, "like", "%%%s%%" % txt])
560
Ankush Menat494bd9e2022-03-28 18:52:46 +0530561 return frappe.desk.reportview.execute(
Sagar Vora9baa2222022-08-03 05:42:30 +0000562 doctype,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530563 filters=filter_list,
564 fields=["name", "parent_account"],
565 limit_start=start,
566 limit_page_length=page_len,
567 as_list=True,
568 )
569
Anand Doshifaefeaa2014-06-24 18:53:04 +0530570
Chinmay D. Paiaa121092020-07-01 21:14:32 +0530571@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530572@frappe.validate_and_sanitize_search_inputs
Marica299e2172020-04-28 13:00:04 +0530573def get_blanket_orders(doctype, txt, searchfield, start, page_len, filters):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530574 return frappe.db.sql(
575 """select distinct bo.name, bo.blanket_order_type, bo.to_date
Marica299e2172020-04-28 13:00:04 +0530576 from `tabBlanket Order` bo, `tabBlanket Order Item` boi
577 where
578 boi.parent = bo.name
579 and boi.item_code = {item_code}
580 and bo.blanket_order_type = '{blanket_order_type}'
581 and bo.company = {company}
Ankush Menat494bd9e2022-03-28 18:52:46 +0530582 and bo.docstatus = 1""".format(
583 item_code=frappe.db.escape(filters.get("item")),
584 blanket_order_type=filters.get("blanket_order_type"),
585 company=frappe.db.escape(filters.get("company")),
586 )
587 )
Nabin Haitafd14f62015-10-19 11:55:28 +0530588
Himanshud94a38e2020-05-18 14:26:26 +0530589
Nabin Haitafd14f62015-10-19 11:55:28 +0530590@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530591@frappe.validate_and_sanitize_search_inputs
Nabin Haitafd14f62015-10-19 11:55:28 +0530592def get_income_account(doctype, txt, searchfield, start, page_len, filters):
593 from erpnext.controllers.queries import get_match_cond
594
595 # income account can be any Credit account,
596 # but can also be a Asset account with account_type='Income Account' in special circumstances.
597 # Hence the first condition is an "OR"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530598 if not filters:
599 filters = {}
Nabin Haitafd14f62015-10-19 11:55:28 +0530600
Sagar Vora9baa2222022-08-03 05:42:30 +0000601 doctype = "Account"
Anand Doshi21e09a22015-10-29 12:21:41 +0530602 condition = ""
Nabin Haitafd14f62015-10-19 11:55:28 +0530603 if filters.get("company"):
604 condition += "and tabAccount.company = %(company)s"
Anand Doshi21e09a22015-10-29 12:21:41 +0530605
ruthra kumar6e3e0942023-11-02 17:19:06 +0530606 condition += f"and tabAccount.disabled = {filters.get('disabled', 0)}"
607
Ankush Menat494bd9e2022-03-28 18:52:46 +0530608 return frappe.db.sql(
609 """select tabAccount.name from `tabAccount`
Nabin Haitafd14f62015-10-19 11:55:28 +0530610 where (tabAccount.report_type = "Profit and Loss"
611 or tabAccount.account_type in ("Income Account", "Temporary"))
612 and tabAccount.is_group=0
613 and tabAccount.`{key}` LIKE %(txt)s
Rushabh Mehta3574b372016-03-11 14:33:04 +0530614 {condition} {match_condition}
Ankush Menat494bd9e2022-03-28 18:52:46 +0530615 order by idx desc, name""".format(
616 condition=condition, match_condition=get_match_cond(doctype), key=searchfield
617 ),
618 {"txt": "%" + txt + "%", "company": filters.get("company", "")},
619 )
620
Nabin Hait3a15c922016-03-04 12:30:46 +0530621
Deepesh Garg96e874b2020-11-15 22:43:01 +0530622@frappe.whitelist()
623@frappe.validate_and_sanitize_search_inputs
Ankush Menat6de71eb2023-04-25 18:33:31 +0530624def get_filtered_dimensions(
625 doctype, txt, searchfield, start, page_len, filters, reference_doctype=None
626):
Chillar Anand915b3432021-09-02 16:44:59 +0530627 from erpnext.accounts.doctype.accounting_dimension_filter.accounting_dimension_filter import (
628 get_dimension_filter_map,
629 )
Ankush Menat494bd9e2022-03-28 18:52:46 +0530630
Deepesh Garg96e874b2020-11-15 22:43:01 +0530631 dimension_filters = get_dimension_filter_map()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530632 dimension_filters = dimension_filters.get((filters.get("dimension"), filters.get("account")))
Deepesh Garg6c17b842020-11-25 13:42:16 +0530633 query_filters = []
mergify[bot]071118f2021-11-30 13:15:20 +0000634 or_filters = []
Ankush Menat494bd9e2022-03-28 18:52:46 +0530635 fields = ["name"]
mergify[bot]071118f2021-11-30 13:15:20 +0000636
637 searchfields = frappe.get_meta(doctype).get_search_fields()
Deepesh Garg96e874b2020-11-15 22:43:01 +0530638
639 meta = frappe.get_meta(doctype)
Deepesh Garg96e874b2020-11-15 22:43:01 +0530640 if meta.is_tree:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530641 query_filters.append(["is_group", "=", 0])
Deepesh Garg96e874b2020-11-15 22:43:01 +0530642
Ankush Menat494bd9e2022-03-28 18:52:46 +0530643 if meta.has_field("disabled"):
644 query_filters.append(["disabled", "!=", 1])
Subin Tom333e44e2021-08-18 16:17:54 +0530645
Ankush Menat494bd9e2022-03-28 18:52:46 +0530646 if meta.has_field("company"):
647 query_filters.append(["company", "=", filters.get("company")])
Deepesh Garg6c17b842020-11-25 13:42:16 +0530648
mergify[bot]071118f2021-11-30 13:15:20 +0000649 for field in searchfields:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530650 or_filters.append([field, "LIKE", "%%%s%%" % txt])
mergify[bot]071118f2021-11-30 13:15:20 +0000651 fields.append(field)
Deepesh Garg96e874b2020-11-15 22:43:01 +0530652
653 if dimension_filters:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530654 if dimension_filters["allow_or_restrict"] == "Allow":
655 query_selector = "in"
Deepesh Garg96e874b2020-11-15 22:43:01 +0530656 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530657 query_selector = "not in"
Deepesh Garg96e874b2020-11-15 22:43:01 +0530658
Ankush Menat494bd9e2022-03-28 18:52:46 +0530659 if len(dimension_filters["allowed_dimensions"]) == 1:
660 dimensions = tuple(dimension_filters["allowed_dimensions"] * 2)
Deepesh Garg96e874b2020-11-15 22:43:01 +0530661 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530662 dimensions = tuple(dimension_filters["allowed_dimensions"])
Deepesh Garg96e874b2020-11-15 22:43:01 +0530663
Ankush Menat494bd9e2022-03-28 18:52:46 +0530664 query_filters.append(["name", query_selector, dimensions])
Deepesh Garg96e874b2020-11-15 22:43:01 +0530665
Ankush Menat494bd9e2022-03-28 18:52:46 +0530666 output = frappe.get_list(
Ankush Menat6de71eb2023-04-25 18:33:31 +0530667 doctype,
668 fields=fields,
669 filters=query_filters,
670 or_filters=or_filters,
671 as_list=1,
672 reference_doctype=reference_doctype,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530673 )
Deepesh Garg6c17b842020-11-25 13:42:16 +0530674
mergify[bot]071118f2021-11-30 13:15:20 +0000675 return [tuple(d) for d in set(output)]
Nabin Hait3a15c922016-03-04 12:30:46 +0530676
Ankush Menat494bd9e2022-03-28 18:52:46 +0530677
Nabin Hait3a15c922016-03-04 12:30:46 +0530678@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530679@frappe.validate_and_sanitize_search_inputs
Nabin Hait3a15c922016-03-04 12:30:46 +0530680def get_expense_account(doctype, txt, searchfield, start, page_len, filters):
681 from erpnext.controllers.queries import get_match_cond
Rushabh Mehta203cc962016-04-07 15:25:43 +0530682
Ankush Menat494bd9e2022-03-28 18:52:46 +0530683 if not filters:
684 filters = {}
Nabin Hait3a15c922016-03-04 12:30:46 +0530685
Sagar Vora9baa2222022-08-03 05:42:30 +0000686 doctype = "Account"
Nabin Hait3a15c922016-03-04 12:30:46 +0530687 condition = ""
688 if filters.get("company"):
689 condition += "and tabAccount.company = %(company)s"
Rushabh Mehta203cc962016-04-07 15:25:43 +0530690
Ankush Menat494bd9e2022-03-28 18:52:46 +0530691 return frappe.db.sql(
692 """select tabAccount.name from `tabAccount`
Nabin Hait3a15c922016-03-04 12:30:46 +0530693 where (tabAccount.report_type = "Profit and Loss"
Mangesh-Khairnar5619db22019-08-21 14:49:24 +0530694 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 +0530695 and tabAccount.is_group=0
696 and tabAccount.docstatus!=2
697 and tabAccount.{key} LIKE %(txt)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530698 {condition} {match_condition}""".format(
699 condition=condition, key=searchfield, match_condition=get_match_cond(doctype)
700 ),
701 {"company": filters.get("company", ""), "txt": "%" + txt + "%"},
702 )
suyashphadtare049a88c2017-01-12 17:49:37 +0530703
704
705@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530706@frappe.validate_and_sanitize_search_inputs
suyashphadtare049a88c2017-01-12 17:49:37 +0530707def warehouse_query(doctype, txt, searchfield, start, page_len, filters):
708 # Should be used when item code is passed in filters.
Sagar Vora9baa2222022-08-03 05:42:30 +0000709 doctype = "Warehouse"
suyashphadtare750a0672017-01-18 15:35:01 +0530710 conditions, bin_conditions = [], []
711 filter_dict = get_doctype_wise_filters(filters)
712
s-aga-ree14faa2024-02-05 21:53:25 +0530713 warehouse_field = "name"
714 meta = frappe.get_meta("Warehouse")
715 if meta.get("show_title_field_in_link") and meta.get("title_field"):
716 searchfield = meta.get("title_field")
717 warehouse_field = meta.get("title_field")
718
719 query = """select `tabWarehouse`.`{warehouse_field}`,
Conor74a782d2022-06-17 06:31:27 -0500720 CONCAT_WS(' : ', 'Actual Qty', ifnull(round(`tabBin`.actual_qty, 2), 0 )) actual_qty
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530721 from `tabWarehouse` left join `tabBin`
722 on `tabBin`.warehouse = `tabWarehouse`.name {bin_conditions}
suyashphadtare34ab1362017-01-31 15:14:44 +0530723 where
Diksha Jadhav182ee5e2020-08-18 00:35:04 +0530724 `tabWarehouse`.`{key}` like {txt}
suyashphadtare34ab1362017-01-31 15:14:44 +0530725 {fcond} {mcond}
s-aga-ree14faa2024-02-05 21:53:25 +0530726 order by ifnull(`tabBin`.actual_qty, 0) desc, `tabWarehouse`.`{warehouse_field}` asc
suyashphadtare34ab1362017-01-31 15:14:44 +0530727 limit
Conor00ef4992022-06-14 00:19:07 -0500728 {page_len} offset {start}
suyashphadtare34ab1362017-01-31 15:14:44 +0530729 """.format(
s-aga-ree14faa2024-02-05 21:53:25 +0530730 warehouse_field=warehouse_field,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530731 bin_conditions=get_filters_cond(
732 doctype, filter_dict.get("Bin"), bin_conditions, ignore_permissions=True
733 ),
734 key=searchfield,
735 fcond=get_filters_cond(doctype, filter_dict.get("Warehouse"), conditions),
736 mcond=get_match_cond(doctype),
737 start=start,
738 page_len=page_len,
739 txt=frappe.db.escape("%{0}%".format(txt)),
740 )
Rushabh Mehta7e506af2017-08-24 15:23:33 +0530741
742 return frappe.db.sql(query)
suyashphadtare750a0672017-01-18 15:35:01 +0530743
744
745def get_doctype_wise_filters(filters):
746 # Helper function to seperate filters doctype_wise
747 filter_dict = defaultdict(list)
748 for row in filters:
749 filter_dict[row[0]].append(row)
750 return filter_dict
tundebabzy2a4fefc2017-11-29 06:23:09 +0100751
752
753@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530754@frappe.validate_and_sanitize_search_inputs
tundebabzy2a4fefc2017-11-29 06:23:09 +0100755def get_batch_numbers(doctype, txt, searchfield, start, page_len, filters):
rohitwaghchaure9fbed562018-01-12 16:22:33 +0530756 query = """select batch_id from `tabBatch`
Doridel Cahanap59e4c322018-08-06 17:15:18 +0800757 where disabled = 0
Conorb8f728a2022-06-15 01:37:33 -0500758 and (expiry_date >= CURRENT_DATE or expiry_date IS NULL)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530759 and name like {txt}""".format(
760 txt=frappe.db.escape("%{0}%".format(txt))
761 )
tundebabzy2a4fefc2017-11-29 06:23:09 +0100762
Ankush Menat494bd9e2022-03-28 18:52:46 +0530763 if filters and filters.get("item"):
764 query += " and item = {item}".format(item=frappe.db.escape(filters.get("item")))
tundebabzy2a4fefc2017-11-29 06:23:09 +0100765
Sachin Mane64f48db2018-01-08 17:57:32 +0530766 return frappe.db.sql(query, filters)
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530767
Himanshud94a38e2020-05-18 14:26:26 +0530768
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530769@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530770@frappe.validate_and_sanitize_search_inputs
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530771def item_manufacturer_query(doctype, txt, searchfield, start, page_len, filters):
Maricabac4b932019-09-16 19:44:28 +0530772 item_filters = [
Ankush Menat494bd9e2022-03-28 18:52:46 +0530773 ["manufacturer", "like", "%" + txt + "%"],
774 ["item_code", "=", filters.get("item_code")],
Maricabac4b932019-09-16 19:44:28 +0530775 ]
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530776
Maricabac4b932019-09-16 19:44:28 +0530777 item_manufacturers = frappe.get_all(
778 "Item Manufacturer",
779 fields=["manufacturer", "manufacturer_part_no"],
780 filters=item_filters,
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530781 limit_start=start,
782 limit_page_length=page_len,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530783 as_list=1,
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530784 )
Maricabac4b932019-09-16 19:44:28 +0530785 return item_manufacturers
Saqibd9956092019-11-18 11:46:55 +0530786
Himanshud94a38e2020-05-18 14:26:26 +0530787
Saqibd9956092019-11-18 11:46:55 +0530788@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530789@frappe.validate_and_sanitize_search_inputs
Saqibd9956092019-11-18 11:46:55 +0530790def get_purchase_receipts(doctype, txt, searchfield, start, page_len, filters):
791 query = """
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530792 select pr.name
Saqibd9956092019-11-18 11:46:55 +0530793 from `tabPurchase Receipt` pr, `tabPurchase Receipt Item` pritem
794 where pr.docstatus = 1 and pritem.parent = pr.name
Ankush Menat494bd9e2022-03-28 18:52:46 +0530795 and pr.name like {txt}""".format(
796 txt=frappe.db.escape("%{0}%".format(txt))
797 )
Saqibd9956092019-11-18 11:46:55 +0530798
Ankush Menat494bd9e2022-03-28 18:52:46 +0530799 if filters and filters.get("item_code"):
800 query += " and pritem.item_code = {item_code}".format(
801 item_code=frappe.db.escape(filters.get("item_code"))
802 )
Saqibd9956092019-11-18 11:46:55 +0530803
804 return frappe.db.sql(query, filters)
805
Himanshud94a38e2020-05-18 14:26:26 +0530806
Saqibd9956092019-11-18 11:46:55 +0530807@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530808@frappe.validate_and_sanitize_search_inputs
Saqibd9956092019-11-18 11:46:55 +0530809def get_purchase_invoices(doctype, txt, searchfield, start, page_len, filters):
810 query = """
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530811 select pi.name
Saqibd9956092019-11-18 11:46:55 +0530812 from `tabPurchase Invoice` pi, `tabPurchase Invoice Item` piitem
813 where pi.docstatus = 1 and piitem.parent = pi.name
Ankush Menat494bd9e2022-03-28 18:52:46 +0530814 and pi.name like {txt}""".format(
815 txt=frappe.db.escape("%{0}%".format(txt))
816 )
Saqibd9956092019-11-18 11:46:55 +0530817
Ankush Menat494bd9e2022-03-28 18:52:46 +0530818 if filters and filters.get("item_code"):
819 query += " and piitem.item_code = {item_code}".format(
820 item_code=frappe.db.escape(filters.get("item_code"))
821 )
Saqibd9956092019-11-18 11:46:55 +0530822
823 return frappe.db.sql(query, filters)
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530824
Himanshud94a38e2020-05-18 14:26:26 +0530825
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530826@frappe.whitelist()
Suraj Shetty1923ef02020-08-05 19:42:25 +0530827@frappe.validate_and_sanitize_search_inputs
mergify[bot]b4db5e92023-07-18 17:40:49 +0530828def get_doctypes_for_closing(doctype, txt, searchfield, start, page_len, filters):
829 doctypes = frappe.get_hooks("period_closing_doctypes")
830 if txt:
831 doctypes = [d for d in doctypes if txt.lower() in d.lower()]
832 return [(d,) for d in set(doctypes)]
833
834
835@frappe.whitelist()
836@frappe.validate_and_sanitize_search_inputs
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530837def get_tax_template(doctype, txt, searchfield, start, page_len, filters):
838
Ankush Menat494bd9e2022-03-28 18:52:46 +0530839 item_doc = frappe.get_cached_doc("Item", filters.get("item_code"))
840 item_group = filters.get("item_group")
841 company = filters.get("company")
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530842 taxes = item_doc.taxes or []
843
844 while item_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530845 item_group_doc = frappe.get_cached_doc("Item Group", item_group)
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530846 taxes += item_group_doc.taxes or []
847 item_group = item_group_doc.parent_item_group
848
849 if not taxes:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530850 return frappe.get_all(
851 "Item Tax Template", filters={"disabled": 0, "company": company}, as_list=True
852 )
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530853 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530854 valid_from = filters.get("valid_from")
Marica0fcb05a2020-08-10 14:48:13 +0530855 valid_from = valid_from[1] if isinstance(valid_from, list) else valid_from
856
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530857 args = {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530858 "item_code": filters.get("item_code"),
859 "posting_date": valid_from,
860 "tax_category": filters.get("tax_category"),
861 "company": company,
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530862 }
863
864 taxes = _get_item_tax_template(args, taxes, for_validate=True)
865 return [(d,) for d in set(taxes)]
Himanshud94a38e2020-05-18 14:26:26 +0530866
867
Ankush Menat7eac4a22021-04-19 10:33:39 +0530868def get_fields(doctype, fields=None):
869 if fields is None:
870 fields = []
Himanshud94a38e2020-05-18 14:26:26 +0530871 meta = frappe.get_meta(doctype)
872 fields.extend(meta.get_search_fields())
873
barredterraeb9ee3f2023-12-05 11:22:55 +0100874 if meta.title_field and meta.title_field.strip() not in fields:
Himanshud94a38e2020-05-18 14:26:26 +0530875 fields.insert(1, meta.title_field.strip())
876
877 return unique(fields)
ruthra kumar662ccd42023-07-22 11:18:11 +0530878
879
880@frappe.whitelist()
881@frappe.validate_and_sanitize_search_inputs
882def get_payment_terms_for_references(doctype, txt, searchfield, start, page_len, filters) -> list:
883 terms = []
884 if filters:
885 terms = frappe.db.get_all(
886 "Payment Schedule",
887 filters={"parent": filters.get("reference")},
888 fields=["payment_term"],
889 limit=page_len,
890 as_list=1,
891 )
892 return terms
s-aga-r00261092023-12-04 18:00:06 +0530893
894
895@frappe.whitelist()
896@frappe.validate_and_sanitize_search_inputs
897def get_filtered_child_rows(doctype, txt, searchfield, start, page_len, filters) -> list:
898 table = frappe.qb.DocType(doctype)
899 query = (
900 frappe.qb.from_(table)
901 .select(
902 table.name,
903 Concat("#", table.idx, ", ", table.item_code),
904 )
905 .orderby(table.idx)
906 .offset(start)
907 .limit(page_len)
908 )
909
910 if filters:
911 for field, value in filters.items():
912 query = query.where(table[field] == value)
913
914 if txt:
915 txt += "%"
916 query = query.where(
917 ((table.idx.like(txt.replace("#", ""))) | (table.item_code.like(txt))) | (table.name.like(txt))
918 )
919
920 return query.run(as_dict=False)