blob: 61b8f353da98e41033b4426a9afaca84579df078 [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
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05303frappe.provide("erpnext");
Nabin Haitb072c742014-12-16 12:49:13 +05304frappe.provide("erpnext.utils");
Anand Doshie65e6212012-11-19 15:43:18 +05305
Anand Doshibdee6e02013-07-09 13:03:39 +05306$.extend(erpnext, {
7 get_currency: function(company) {
8 if(!company && cur_frm)
9 company = cur_frm.doc.company;
10 if(company)
ruthra kumarfa2d33c2023-12-12 15:43:39 +053011 return frappe.get_doc(":Company", company)?.default_currency || frappe.boot.sysdefaults.currency;
Anand Doshibdee6e02013-07-09 13:03:39 +053012 else
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053013 return frappe.boot.sysdefaults.currency;
Anand Doshibdee6e02013-07-09 13:03:39 +053014 },
Rushabh Mehtac38fc712014-04-16 17:21:25 +053015
tundebabzyc8978252018-02-12 10:34:50 +010016 get_presentation_currency_list: () => {
17 const docs = frappe.boot.docs;
Zarrare25dcd22018-06-21 10:53:12 +053018 let currency_list = docs.filter(d => d.doctype === ":Currency").map(d => d.name);
19 currency_list.unshift("");
tundebabzyc8978252018-02-12 10:34:50 +010020 return currency_list;
21 },
22
Anand Doshi8bde7f92014-04-24 18:11:49 +053023 toggle_naming_series: function() {
ruthra kumar60b26ad2024-01-15 20:22:30 +053024 if(cur_frm && cur_frm.fields_dict.naming_series) {
Anand Doshibdee6e02013-07-09 13:03:39 +053025 cur_frm.toggle_display("naming_series", cur_frm.doc.__islocal?true:false);
26 }
27 },
Rushabh Mehtac38fc712014-04-16 17:21:25 +053028
Gursheen Anandceeb8fc2024-02-27 13:05:29 +053029 hide_company: function(frm) {
30 if(frm?.fields_dict.company) {
Rushabh Mehta89418412013-10-07 18:22:29 +053031 var companies = Object.keys(locals[":Company"] || {});
Anand Doshibdee6e02013-07-09 13:03:39 +053032 if(companies.length === 1) {
Gursheen Anandceeb8fc2024-02-27 13:05:29 +053033 if(!frm.doc.company) frm.set_value("company", companies[0]);
34 frm.toggle_display("company", false);
Rushabh Mehta45ca8a42015-04-28 16:02:09 +053035 } else if(erpnext.last_selected_company) {
Gursheen Anandceeb8fc2024-02-27 13:05:29 +053036 if(!frm.doc.company) frm.set_value("company", erpnext.last_selected_company);
Anand Doshibdee6e02013-07-09 13:03:39 +053037 }
38 }
Anand Doshi1ffc5b52013-07-15 18:09:43 +053039 },
Rushabh Mehtac38fc712014-04-16 17:21:25 +053040
Rohit Waghchauree9ff1912017-06-19 12:54:59 +053041 is_perpetual_inventory_enabled: function(company) {
42 if(company) {
Rohit Waghchaure44ed52c2024-02-24 15:33:59 +053043 let company_local = locals[":Company"] && locals[":Company"][company];
44 if(company_local) {
45 return cint(company_local.enable_perpetual_inventory);
46 }
Rohit Waghchauree9ff1912017-06-19 12:54:59 +053047 }
48 },
49
Makarand Bauskare6712c12017-10-25 12:17:40 +053050 stale_rate_allowed: () => {
rohitwaghchaure7677ff02017-11-02 18:12:14 +053051 return cint(frappe.boot.sysdefaults.allow_stale);
Makarand Bauskare6712c12017-10-25 12:17:40 +053052 },
53
Alanc6dc9ea2021-05-07 20:30:04 +053054 setup_serial_or_batch_no: function() {
55 let grid_row = cur_frm.open_grid_row();
56 if (!grid_row || !grid_row.grid_form.fields_dict.serial_no ||
57 grid_row.grid_form.fields_dict.serial_no.get_status() !== "Write") return;
Rushabh Mehtac38fc712014-04-16 17:21:25 +053058
Alanc6dc9ea2021-05-07 20:30:04 +053059 frappe.model.get_value('Item', {'name': grid_row.doc.item_code},
60 ['has_serial_no', 'has_batch_no'], ({has_serial_no, has_batch_no}) => {
61 Object.assign(grid_row.doc, {has_serial_no, has_batch_no});
Rushabh Mehtac38fc712014-04-16 17:21:25 +053062
Alanc6dc9ea2021-05-07 20:30:04 +053063 if (has_serial_no) {
64 attach_selector_button(__("Add Serial No"),
65 grid_row.grid_form.fields_dict.serial_no.$wrapper, this, grid_row);
66 } else if (has_batch_no) {
67 attach_selector_button(__("Pick Batch No"),
68 grid_row.grid_form.fields_dict.batch_no.$wrapper, this, grid_row);
Marica29a2e162019-11-12 14:43:41 +053069 }
Alanc6dc9ea2021-05-07 20:30:04 +053070 }
71 );
deepeshgarg007e64c3572019-05-14 08:50:45 +053072 },
Nabin Hait1ed1c4e2019-11-25 12:33:40 +053073
74 route_to_adjustment_jv: (args) => {
75 frappe.model.with_doctype('Journal Entry', () => {
76 // route to adjustment Journal Entry to handle Account Balance and Stock Value mismatch
77 let journal_entry = frappe.model.get_new_doc('Journal Entry');
78
79 args.accounts.forEach((je_account) => {
80 let child_row = frappe.model.add_child(journal_entry, "accounts");
81 child_row.account = je_account.account;
82 child_row.debit_in_account_currency = je_account.debit_in_account_currency;
83 child_row.credit_in_account_currency = je_account.credit_in_account_currency;
84 child_row.party_type = "" ;
85 });
86 frappe.set_route('Form','Journal Entry', journal_entry.name);
87 });
Frappe PR Bot255b99e2021-08-24 20:19:22 +053088 },
89
Ankush Menatd37541d2021-12-10 12:04:10 +053090 route_to_pending_reposts: (args) => {
91 frappe.set_route('List', 'Repost Item Valuation', args);
92 },
Rushabh Mehtac38fc712014-04-16 17:21:25 +053093});
Rushabh Mehta7d368752014-11-24 14:16:47 +053094
Nabin Haitb072c742014-12-16 12:49:13 +053095
96$.extend(erpnext.utils, {
Rushabh Mehta559aa3a2016-09-19 16:04:58 +053097 set_party_dashboard_indicators: function(frm) {
98 if(frm.doc.__onload && frm.doc.__onload.dashboard_info) {
deepeshgarg007920dc142018-11-23 10:17:28 +053099 var company_wise_info = frm.doc.__onload.dashboard_info;
deepeshgarg007f31caff2018-11-27 15:04:12 +0530100 if(company_wise_info.length > 1) {
deepeshgarg007a1cffc32018-11-23 16:51:35 +0530101 company_wise_info.forEach(function(info) {
deepeshgarg00712f5cef2018-12-25 16:06:19 +0530102 erpnext.utils.add_indicator_for_multicompany(frm, info);
deepeshgarg007a1cffc32018-11-23 16:51:35 +0530103 });
deepeshgarg00712f5cef2018-12-25 16:06:19 +0530104 } else if (company_wise_info.length === 1) {
deepeshgarg00764238ee2018-12-25 16:28:39 +0530105 frm.dashboard.add_indicator(__('Annual Billing: {0}',
106 [format_currency(company_wise_info[0].billing_this_year, company_wise_info[0].currency)]), 'blue');
107 frm.dashboard.add_indicator(__('Total Unpaid: {0}',
108 [format_currency(company_wise_info[0].total_unpaid, company_wise_info[0].currency)]),
deepeshgarg0078300f5e2019-01-01 20:28:49 +0530109 company_wise_info[0].total_unpaid ? 'orange' : 'green');
deepeshgarg00712f5cef2018-12-25 16:06:19 +0530110
deepeshgarg00764238ee2018-12-25 16:28:39 +0530111 if(company_wise_info[0].loyalty_points) {
112 frm.dashboard.add_indicator(__('Loyalty Points: {0}',
113 [company_wise_info[0].loyalty_points]), 'blue');
114 }
deepeshgarg007f31caff2018-11-27 15:04:12 +0530115 }
Rushabh Mehta559aa3a2016-09-19 16:04:58 +0530116 }
117 },
118
Rohit Waghchaure708eefb2023-07-10 16:54:55 +0530119 view_serial_batch_nos: function(frm) {
rohitwaghchaure3c15fea2023-08-24 17:24:44 +0530120 if (!frm.doc?.items) {
121 return;
122 }
123
Rohit Waghchaure708eefb2023-07-10 16:54:55 +0530124 let bundle_ids = frm.doc.items.filter(d => d.serial_and_batch_bundle);
125
126 if (bundle_ids?.length) {
127 frm.add_custom_button(__('Serial / Batch Nos'), () => {
128 frappe.route_options = {
129 "voucher_no": frm.doc.name,
130 "voucher_type": frm.doc.doctype,
131 "from_date": frm.doc.posting_date || frm.doc.transaction_date,
132 "to_date": frm.doc.posting_date || frm.doc.transaction_date,
133 "company": frm.doc.company,
134 };
135 frappe.set_route("query-report", "Serial and Batch Summary");
136 }, __('View'));
137 }
138 },
139
deepeshgarg00712f5cef2018-12-25 16:06:19 +0530140 add_indicator_for_multicompany: function(frm, info) {
Deepak867f2c62022-05-17 11:52:52 +0530141 frm.dashboard.stats_area.show();
deepeshgarg00712f5cef2018-12-25 16:06:19 +0530142 frm.dashboard.stats_area_row.addClass('flex');
143 frm.dashboard.stats_area_row.css('flex-wrap', 'wrap');
144
145 var color = info.total_unpaid ? 'orange' : 'green';
146
147 var indicator = $('<div class="flex-column col-xs-6">'+
148 '<div style="margin-top:10px"><h6>'+info.company+'</h6></div>'+
149
150 '<div class="badge-link small" style="margin-bottom:10px"><span class="indicator blue">'+
151 'Annual Billing: '+format_currency(info.billing_this_year, info.currency)+'</span></div>'+
152
153 '<div class="badge-link small" style="margin-bottom:10px">'+
154 '<span class="indicator '+color+'">Total Unpaid: '
155 +format_currency(info.total_unpaid, info.currency)+'</span></div>'+
156
157
158 '</div>').appendTo(frm.dashboard.stats_area_row);
159
160 if(info.loyalty_points){
161 $('<div class="badge-link small" style="margin-bottom:10px"><span class="indicator blue">'+
162 'Loyalty Points: '+info.loyalty_points+'</span></div>').appendTo(indicator);
163 }
164
165 return indicator;
166 },
167
Shreya Shah149f7ee2018-03-27 11:29:25 +0530168 get_party_name: function(party_type) {
169 var dict = {'Customer': 'customer_name', 'Supplier': 'supplier_name', 'Employee': 'employee_name',
170 'Member': 'member_name'};
171 return dict[party_type];
172 },
173
Rushabh Mehta49f97472018-08-30 18:50:48 +0530174 copy_value_in_all_rows: function(doc, dt, dn, table_fieldname, fieldname) {
Neil Trini Lasradofe2ffae2015-07-08 18:16:51 +0530175 var d = locals[dt][dn];
176 if(d[fieldname]){
177 var cl = doc[table_fieldname] || [];
178 for(var i = 0; i < cl.length; i++) {
179 if(!cl[i][fieldname]) cl[i][fieldname] = d[fieldname];
180 }
181 }
182 refresh_field(table_fieldname);
Makarand Bauskar157c3342017-05-26 21:32:33 +0530183 },
184
185 get_terms: function(tc_name, doc, callback) {
186 if(tc_name) {
187 return frappe.call({
188 method: 'erpnext.setup.doctype.terms_and_conditions.terms_and_conditions.get_terms_and_conditions',
189 args: {
190 template_name: tc_name,
191 doc: doc
192 },
193 callback: function(r) {
194 callback(r)
195 }
196 });
197 }
tundebabzy1a947db2017-08-29 13:48:27 +0100198 },
199
rohitwaghchaure713cfc72018-09-11 17:40:37 +0530200 make_bank_account: function(doctype, docname) {
201 frappe.call({
202 method: "erpnext.accounts.doctype.bank_account.bank_account.make_bank_account",
203 args: {
204 doctype: doctype,
205 docname: docname
206 },
207 freeze: true,
208 callback: function(r) {
209 var doclist = frappe.model.sync(r.message);
210 frappe.set_route("Form", doclist[0].doctype, doclist[0].name);
211 }
212 })
213 },
214
Deepesh Garg11ea0b12020-05-26 19:23:45 +0530215 add_dimensions: function(report_name, index) {
216 let filters = frappe.query_reports[report_name].filters;
217
Deepesh Garg7b2d5182020-12-04 11:28:26 +0530218 frappe.call({
219 method: "erpnext.accounts.doctype.accounting_dimension.accounting_dimension.get_dimensions",
220 callback: function(r) {
221 let accounting_dimensions = r.message[0];
222 accounting_dimensions.forEach((dimension) => {
223 let found = filters.some(el => el.fieldname === dimension['fieldname']);
Deepesh Garg11ea0b12020-05-26 19:23:45 +0530224
Deepesh Garg7b2d5182020-12-04 11:28:26 +0530225 if (!found) {
Deepesh Garg23ab5c52020-12-31 11:29:06 +0530226 filters.splice(index, 0, {
Deepesh Garg7b2d5182020-12-04 11:28:26 +0530227 "fieldname": dimension["fieldname"],
228 "label": __(dimension["label"]),
Rohit Waghchaure69be22b2022-05-14 17:19:34 +0530229 "fieldtype": "MultiSelectList",
230 get_data: function(txt) {
231 return frappe.db.get_link_options(dimension["document_type"], txt);
232 },
Deepesh Garg7b2d5182020-12-04 11:28:26 +0530233 });
234 }
Deepesh Garg11ea0b12020-05-26 19:23:45 +0530235 });
236 }
237 });
238 },
239
Rohit Waghchauredbec5cf2022-06-22 12:24:08 +0530240 add_inventory_dimensions: function(report_name, index) {
241 let filters = frappe.query_reports[report_name].filters;
242
243 frappe.call({
244 method: "erpnext.stock.doctype.inventory_dimension.inventory_dimension.get_inventory_dimensions",
245 callback: function(r) {
246 if (r.message && r.message.length) {
247 r.message.forEach((dimension) => {
Rohit Waghchaure0e388ba2023-02-20 12:20:03 +0530248 let existing_filter = filters.filter(el => el.fieldname === dimension['fieldname']);
Rohit Waghchauredbec5cf2022-06-22 12:24:08 +0530249
Rohit Waghchaure0e388ba2023-02-20 12:20:03 +0530250 if (!existing_filter.length) {
Rohit Waghchauredbec5cf2022-06-22 12:24:08 +0530251 filters.splice(index, 0, {
252 "fieldname": dimension["fieldname"],
Rohit Waghchaureef7def82022-09-07 14:40:18 +0530253 "label": __(dimension["doctype"]),
Rohit Waghchauredbec5cf2022-06-22 12:24:08 +0530254 "fieldtype": "MultiSelectList",
255 get_data: function(txt) {
256 return frappe.db.get_link_options(dimension["doctype"], txt);
257 },
258 });
Rohit Waghchaure0e388ba2023-02-20 12:20:03 +0530259 } else {
260 existing_filter[0]['fieldtype'] = "MultiSelectList";
261 existing_filter[0]['get_data'] = function(txt) {
262 return frappe.db.get_link_options(dimension["doctype"], txt);
263 }
Rohit Waghchauredbec5cf2022-06-22 12:24:08 +0530264 }
265 });
266 }
267 }
268 });
269 },
270
rohitwaghchaure166b78f2017-09-07 16:14:22 +0530271 make_subscription: function(doctype, docname) {
272 frappe.call({
Rucha Mahabal65a627c2019-07-17 13:50:32 +0530273 method: "frappe.automation.doctype.auto_repeat.auto_repeat.make_auto_repeat",
rohitwaghchaure166b78f2017-09-07 16:14:22 +0530274 args: {
275 doctype: doctype,
276 docname: docname
277 },
278 callback: function(r) {
279 var doclist = frappe.model.sync(r.message);
280 frappe.set_route("Form", doclist[0].doctype, doclist[0].name);
281 }
282 })
283 },
284
Saif90cf2dd2018-09-30 21:46:31 +0500285 make_pricing_rule: function(doctype, docname) {
286 frappe.call({
287 method: "erpnext.accounts.doctype.pricing_rule.pricing_rule.make_pricing_rule",
288 args: {
289 doctype: doctype,
290 docname: docname
291 },
292 callback: function(r) {
293 var doclist = frappe.model.sync(r.message);
294 frappe.set_route("Form", doclist[0].doctype, doclist[0].name);
295 }
296 })
297 },
298
tundebabzy1a947db2017-08-29 13:48:27 +0100299 /**
300 * Checks if the first row of a given child table is empty
301 * @param child_table - Child table Doctype
302 * @return {Boolean}
303 **/
304 first_row_is_empty: function(child_table){
305 if($.isArray(child_table) && child_table.length > 0) {
306 return !child_table[0].item_code;
307 }
308 return false;
309 },
310
311 /**
312 * Removes the first row of a child table if it is empty
313 * @param {_Frm} frm - The current form
314 * @param {String} child_table_name - The child table field name
315 * @return {Boolean}
316 **/
317 remove_empty_first_row: function(frm, child_table_name){
318 const rows = frm['doc'][child_table_name];
319 if (this.first_row_is_empty(rows)){
320 frm['doc'][child_table_name] = rows.splice(1);
321 }
322 return rows;
323 },
Zarrar6ffdf942018-06-14 12:24:16 +0530324 get_tree_options: function(option) {
325 // get valid options for tree based on user permission & locals dict
326 let unscrub_option = frappe.model.unscrub(option);
327 let user_permission = frappe.defaults.get_user_permissions();
deepeshgarg0070d64d622019-02-20 17:55:14 +0530328 let options;
329
Zarrar6ffdf942018-06-14 12:24:16 +0530330 if(user_permission && user_permission[unscrub_option]) {
deepeshgarg0070d64d622019-02-20 17:55:14 +0530331 options = user_permission[unscrub_option].map(perm => perm.doc);
Zarrar6ffdf942018-06-14 12:24:16 +0530332 } else {
deepeshgarg0070d64d622019-02-20 17:55:14 +0530333 options = $.map(locals[`:${unscrub_option}`], function(c) { return c.name; }).sort();
Zarrar6ffdf942018-06-14 12:24:16 +0530334 }
deepeshgarg0070d64d622019-02-20 17:55:14 +0530335
336 // filter unique values, as there may be multiple user permissions for any value
337 return options.filter((value, index, self) => self.indexOf(value) === index);
Zarrar6ffdf942018-06-14 12:24:16 +0530338 },
339 get_tree_default: function(option) {
340 // set default for a field based on user permission
341 let options = this.get_tree_options(option);
342 if(options.includes(frappe.defaults.get_default(option))) {
343 return frappe.defaults.get_default(option);
344 } else {
345 return options[0];
346 }
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400347 },
Andy Zhubffe9332021-04-12 22:49:26 +1200348 overrides_parent_value_in_all_rows: function(doc, dt, dn, table_fieldname, fieldname, parent_fieldname) {
Marica24e45162021-04-14 18:53:15 +0530349 if (doc[parent_fieldname]) {
Andy Zhubffe9332021-04-12 22:49:26 +1200350 let cl = doc[table_fieldname] || [];
Marica24e45162021-04-14 18:53:15 +0530351 for (let i = 0; i < cl.length; i++) {
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400352 cl[i][fieldname] = doc[parent_fieldname];
353 }
Andy Zhubffe9332021-04-12 22:49:26 +1200354 frappe.refresh_field(table_fieldname);
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400355 }
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400356 },
Nabin Hait34c551d2019-07-03 10:34:31 +0530357 create_new_doc: function (doctype, update_fields) {
358 frappe.model.with_doctype(doctype, function() {
359 var new_doc = frappe.model.get_new_doc(doctype);
360 for (let [key, value] of Object.entries(update_fields)) {
361 new_doc[key] = value;
362 }
363 frappe.ui.form.make_quick_entry(doctype, null, null, new_doc);
364 });
Ankush Menat0b86b1b2022-12-08 16:40:13 +0530365 },
Nabin Hait34c551d2019-07-03 10:34:31 +0530366
Ankush Menat0b86b1b2022-12-08 16:40:13 +0530367 // check if payments app is installed on site, if not warn user.
368 check_payments_app: () => {
369 if (frappe.boot.versions && !frappe.boot.versions.payments) {
370 const marketplace_link = '<a href="https://frappecloud.com/marketplace/apps/payments">Marketplace</a>'
371 const github_link = '<a href="https://github.com/frappe/payments/">GitHub</a>'
372 const msg = __("payments app is not installed. Please install it from {0} or {1}", [marketplace_link, github_link])
373 frappe.msgprint(msg);
374 }
375
376 },
Rohit Waghchaure1c2fe082023-06-15 12:54:43 +0530377
378 pick_serial_and_batch_bundle(frm, cdt, cdn, type_of_transaction, warehouse_field) {
379 let item_row = frappe.get_doc(cdt, cdn);
380 item_row.type_of_transaction = type_of_transaction;
381
382 frappe.db.get_value("Item", item_row.item_code, ["has_batch_no", "has_serial_no"])
383 .then((r) => {
384 item_row.has_batch_no = r.message.has_batch_no;
385 item_row.has_serial_no = r.message.has_serial_no;
386
387 frappe.require("assets/erpnext/js/utils/serial_no_batch_selector.js", function() {
388 new erpnext.SerialBatchPackageSelector(frm, item_row, (r) => {
389 if (r) {
390 let update_values = {
391 "serial_and_batch_bundle": r.name,
392 "qty": Math.abs(r.total_qty)
393 }
394
395 if (!warehouse_field) {
396 warehouse_field = "warehouse";
397 }
398
399 if (r.warehouse) {
400 update_values[warehouse_field] = r.warehouse;
401 }
402
403 frappe.model.set_value(item_row.doctype, item_row.name, update_values);
404 }
405 });
406 });
407 });
Deepesh Garg62706072023-07-16 12:58:42 +0530408 },
409
ruthra kumarc31ee8e2023-11-14 06:44:49 +0530410 get_fiscal_year: function(date, with_dates=false, boolean=false) {
Deepesh Garg3759a412023-07-19 13:17:12 +0530411 if(!date) {
412 date = frappe.datetime.get_today();
413 }
414
Deepesh Garg62706072023-07-16 12:58:42 +0530415 let fiscal_year = '';
416 frappe.call({
417 method: "erpnext.accounts.utils.get_fiscal_year",
418 args: {
ruthra kumarc31ee8e2023-11-14 06:44:49 +0530419 date: date,
420 boolean: boolean
Deepesh Garg62706072023-07-16 12:58:42 +0530421 },
422 async: false,
423 callback: function(r) {
424 if (r.message) {
Deepesh Garg4496a672023-07-24 11:58:16 +0530425 if (with_dates)
426 fiscal_year = r.message;
427 else
428 fiscal_year = r.message[0];
Deepesh Garg62706072023-07-16 12:58:42 +0530429 }
430 }
431 });
432 return fiscal_year;
Rohit Waghchaure1c2fe082023-06-15 12:54:43 +0530433 }
Rushabh Mehta95b995b2015-05-28 12:10:55 +0530434});
435
rohitwaghchaurea3c3dec2018-03-28 11:51:44 +0530436erpnext.utils.select_alternate_items = function(opts) {
437 const frm = opts.frm;
438 const warehouse_field = opts.warehouse_field || 'warehouse';
439 const item_field = opts.item_field || 'item_code';
440
441 this.data = [];
442 const dialog = new frappe.ui.Dialog({
443 title: __("Select Alternate Item"),
444 fields: [
445 {fieldtype:'Section Break', label: __('Items')},
446 {
447 fieldname: "alternative_items", fieldtype: "Table", cannot_add_rows: true,
448 in_place_edit: true, data: this.data,
449 get_data: () => {
450 return this.data;
451 },
452 fields: [{
453 fieldtype:'Data',
454 fieldname:"docname",
455 hidden: 1
456 }, {
457 fieldtype:'Link',
458 fieldname:"item_code",
459 options: 'Item',
460 in_list_view: 1,
461 read_only: 1,
462 label: __('Item Code')
463 }, {
464 fieldtype:'Link',
465 fieldname:"alternate_item",
466 options: 'Item',
467 default: "",
468 in_list_view: 1,
469 label: __('Alternate Item'),
470 onchange: function() {
471 const item_code = this.get_value();
472 const warehouse = this.grid_row.on_grid_fields_dict.warehouse.get_value();
473 if (item_code && warehouse) {
474 frappe.call({
475 method: "erpnext.stock.utils.get_latest_stock_qty",
476 args: {
477 item_code: item_code,
478 warehouse: warehouse
479 },
480 callback: (r) => {
481 this.grid_row.on_grid_fields_dict
482 .actual_qty.set_value(r.message || 0);
483 }
484 })
485 }
486 },
487 get_query: (e) => {
488 return {
489 query: "erpnext.stock.doctype.item_alternative.item_alternative.get_alternative_items",
490 filters: {
491 item_code: e.item_code
492 }
493 };
494 }
495 }, {
496 fieldtype:'Link',
497 fieldname:"warehouse",
498 options: 'Warehouse',
499 default: "",
500 in_list_view: 1,
501 label: __('Warehouse'),
502 onchange: function() {
503 const warehouse = this.get_value();
504 const item_code = this.grid_row.on_grid_fields_dict.item_code.get_value();
505 if (item_code && warehouse) {
506 frappe.call({
507 method: "erpnext.stock.utils.get_latest_stock_qty",
508 args: {
509 item_code: item_code,
510 warehouse: warehouse
511 },
512 callback: (r) => {
513 this.grid_row.on_grid_fields_dict
514 .actual_qty.set_value(r.message || 0);
515 }
516 })
517 }
518 },
519 }, {
520 fieldtype:'Float',
521 fieldname:"actual_qty",
522 default: 0,
523 read_only: 1,
524 in_list_view: 1,
525 label: __('Available Qty')
526 }]
527 },
528 ],
529 primary_action: function() {
530 const args = this.get_values()["alternative_items"];
531 const alternative_items = args.filter(d => {
532 if (d.alternate_item && d.item_code != d.alternate_item) {
533 return true;
534 }
535 });
536
537 alternative_items.forEach(d => {
538 let row = frappe.get_doc(opts.child_doctype, d.docname);
Doridel Cahanape42192b2018-05-16 13:28:39 +0800539 let qty = null;
540 if (row.doctype === 'Work Order Item') {
541 qty = row.required_qty;
542 } else {
543 qty = row.qty;
544 }
rohitwaghchaurea3c3dec2018-03-28 11:51:44 +0530545 row[item_field] = d.alternate_item;
mergify[bot]c1a0f642021-12-17 19:06:19 +0530546 frappe.model.set_value(row.doctype, row.name, 'qty', qty);
547 frappe.model.set_value(row.doctype, row.name, opts.original_item_field, d.item_code);
548 frm.trigger(item_field, row.doctype, row.name);
rohitwaghchaurea3c3dec2018-03-28 11:51:44 +0530549 });
550
551 refresh_field(opts.child_docname);
552 this.hide();
553 },
554 primary_action_label: __('Update')
555 });
556
557 frm.doc[opts.child_docname].forEach(d => {
558 if (!opts.condition || opts.condition(d)) {
559 dialog.fields_dict.alternative_items.df.data.push({
560 "docname": d.name,
561 "item_code": d[item_field],
562 "warehouse": d[warehouse_field],
563 "actual_qty": d.actual_qty
564 });
565 }
566 })
567
568 this.data = dialog.fields_dict.alternative_items.df.data;
569 dialog.fields_dict.alternative_items.grid.refresh();
570 dialog.show();
571}
572
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800573erpnext.utils.update_child_items = function(opts) {
574 const frm = opts.frm;
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +0100575 const cannot_add_row = (typeof opts.cannot_add_row === 'undefined') ? true : opts.cannot_add_row;
576 const child_docname = (typeof opts.cannot_add_row === 'undefined') ? "items" : opts.child_docname;
Saqib56fea7d2020-10-09 21:19:25 +0530577 const child_meta = frappe.get_meta(`${frm.doc.doctype} Item`);
s-aga-r2d8363a2023-09-02 11:02:24 +0530578 const has_reserved_stock = opts.has_reserved_stock ? true : false;
Saqib56fea7d2020-10-09 21:19:25 +0530579 const get_precision = (fieldname) => child_meta.fields.find(f => f.fieldname == fieldname).precision;
580
Devin Slauenwhitea835c1a2023-01-26 16:53:05 -0500581 this.data = frm.doc[opts.child_docname].map((d) => {
582 return {
583 "docname": d.name,
584 "name": d.name,
585 "item_code": d.item_code,
586 "delivery_date": d.delivery_date,
587 "schedule_date": d.schedule_date,
588 "conversion_factor": d.conversion_factor,
589 "qty": d.qty,
590 "rate": d.rate,
s-aga-r9588bb72023-08-21 22:23:57 +0530591 "uom": d.uom,
592 "fg_item": d.fg_item,
593 "fg_item_qty": d.fg_item_qty,
Devin Slauenwhitea835c1a2023-01-26 16:53:05 -0500594 }
595 });
596
Saqib Ansarif53299e2020-04-15 22:08:12 +0530597 const fields = [{
598 fieldtype:'Data',
599 fieldname:"docname",
600 read_only: 1,
601 hidden: 1,
602 }, {
603 fieldtype:'Link',
604 fieldname:"item_code",
605 options: 'Item',
606 in_list_view: 1,
607 read_only: 0,
608 disabled: 0,
Afshandc7280e2021-08-18 17:44:40 +0530609 label: __('Item Code'),
610 get_query: function() {
611 let filters;
612 if (frm.doc.doctype == 'Sales Order') {
613 filters = {"is_sales_item": 1};
614 } else if (frm.doc.doctype == 'Purchase Order') {
Sagar Sharmad074c932022-03-31 19:57:42 +0530615 if (frm.doc.is_subcontracted) {
s-aga-r6d89b2f2022-06-18 15:46:59 +0530616 if (frm.doc.is_old_subcontracting_flow) {
617 filters = {"is_sub_contracted_item": 1};
618 } else {
619 filters = {"is_stock_item": 0};
620 }
Afshandc7280e2021-08-18 17:44:40 +0530621 } else {
622 filters = {"is_purchase_item": 1};
623 }
624 }
625 return {
626 query: "erpnext.controllers.queries.item_query",
627 filters: filters
628 };
629 }
Saqib Ansarif53299e2020-04-15 22:08:12 +0530630 }, {
Saqib61314242020-09-15 11:14:31 +0530631 fieldtype:'Link',
632 fieldname:'uom',
633 options: 'UOM',
634 read_only: 0,
635 label: __('UOM'),
636 reqd: 1,
637 onchange: function () {
638 frappe.call({
639 method: "erpnext.stock.get_item_details.get_conversion_factor",
640 args: { item_code: this.doc.item_code, uom: this.value },
641 callback: r => {
642 if(!r.exc) {
643 if (this.doc.conversion_factor == r.message.conversion_factor) return;
marination4f395cc2020-09-24 12:43:41 +0530644
Saqib61314242020-09-15 11:14:31 +0530645 const docname = this.doc.docname;
646 dialog.fields_dict.trans_items.df.data.some(doc => {
647 if (doc.docname == docname) {
648 doc.conversion_factor = r.message.conversion_factor;
649 dialog.fields_dict.trans_items.grid.refresh();
650 return true;
651 }
652 })
653 }
654 }
655 });
656 }
657 }, {
Saqib Ansarif53299e2020-04-15 22:08:12 +0530658 fieldtype:'Float',
659 fieldname:"qty",
660 default: 0,
661 read_only: 0,
662 in_list_view: 1,
Saqib56fea7d2020-10-09 21:19:25 +0530663 label: __('Qty'),
664 precision: get_precision("qty")
Saqib Ansarif53299e2020-04-15 22:08:12 +0530665 }, {
666 fieldtype:'Currency',
667 fieldname:"rate",
Afshan84184552021-02-24 16:51:11 +0530668 options: "currency",
Saqib Ansarif53299e2020-04-15 22:08:12 +0530669 default: 0,
670 read_only: 0,
671 in_list_view: 1,
Saqib56fea7d2020-10-09 21:19:25 +0530672 label: __('Rate'),
673 precision: get_precision("rate")
Saqib Ansarif53299e2020-04-15 22:08:12 +0530674 }];
675
676 if (frm.doc.doctype == 'Sales Order' || frm.doc.doctype == 'Purchase Order' ) {
677 fields.splice(2, 0, {
678 fieldtype: 'Date',
679 fieldname: frm.doc.doctype == 'Sales Order' ? "delivery_date" : "schedule_date",
680 in_list_view: 1,
Saqib Ansaric579b082020-05-29 22:21:50 +0530681 label: frm.doc.doctype == 'Sales Order' ? __("Delivery Date") : __("Reqd by date"),
Devin Slauenwhitec86dece2023-12-08 19:57:34 +0000682 default: frm.doc.doctype == 'Sales Order' ? frm.doc.delivery_date : frm.doc.schedule_date,
Saqib Ansaric579b082020-05-29 22:21:50 +0530683 reqd: 1
Saqib Ansarif53299e2020-04-15 22:08:12 +0530684 })
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +0530685 fields.splice(3, 0, {
686 fieldtype: 'Float',
687 fieldname: "conversion_factor",
Saqib56fea7d2020-10-09 21:19:25 +0530688 label: __("Conversion Factor"),
689 precision: get_precision('conversion_factor')
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +0530690 })
Saqib Ansarif53299e2020-04-15 22:08:12 +0530691 }
692
s-aga-rfaf9f132023-08-21 15:51:57 +0530693 if (frm.doc.doctype == 'Purchase Order' && frm.doc.is_subcontracted && !frm.doc.is_old_subcontracting_flow) {
694 fields.push({
695 fieldtype:'Link',
696 fieldname:'fg_item',
697 options: 'Item',
698 reqd: 1,
699 in_list_view: 0,
700 read_only: 0,
701 disabled: 0,
702 label: __('Finished Good Item'),
703 get_query: () => {
704 return {
705 filters: {
706 'is_stock_item': 1,
707 'is_sub_contracted_item': 1,
708 'default_bom': ['!=', '']
709 }
710 }
711 },
712 }, {
713 fieldtype:'Float',
714 fieldname:'fg_item_qty',
715 reqd: 1,
716 default: 0,
717 read_only: 0,
718 in_list_view: 0,
719 label: __('Finished Good Item Qty'),
720 precision: get_precision('fg_item_qty')
721 })
722 }
723
Deepesh Garg40772542023-07-22 23:07:18 +0530724 let dialog = new frappe.ui.Dialog({
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800725 title: __("Update Items"),
Raffael Meyerd5fe1432023-07-14 08:57:35 +0200726 size: "extra-large",
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800727 fields: [
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800728 {
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +0100729 fieldname: "trans_items",
730 fieldtype: "Table",
Maricafc96c1a2020-03-06 10:57:59 +0530731 label: "Items",
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +0100732 cannot_add_rows: cannot_add_row,
Saqibbc919e22020-11-05 17:38:35 +0530733 in_place_edit: false,
Maricafc96c1a2020-03-06 10:57:59 +0530734 reqd: 1,
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +0100735 data: this.data,
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800736 get_data: () => {
737 return this.data;
738 },
Saqib Ansarif53299e2020-04-15 22:08:12 +0530739 fields: fields
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800740 },
741 ],
742 primary_action: function() {
s-aga-r2d8363a2023-09-02 11:02:24 +0530743 if (frm.doctype == "Sales Order" && has_reserved_stock) {
744 this.hide();
745 frappe.confirm(
746 __('The reserved stock will be released when you update items. Are you certain you wish to proceed?'),
747 () => this.update_items(),
748 )
749 } else {
750 this.update_items();
751 }
752 },
753 update_items: function() {
Ankush Menat6de7b8e2021-08-24 12:18:40 +0530754 const trans_items = this.get_values()["trans_items"].filter((item) => !!item.item_code);
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800755 frappe.call({
756 method: 'erpnext.controllers.accounts_controller.update_child_qty_rate',
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +0100757 freeze: true,
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800758 args: {
759 'parent_doctype': frm.doc.doctype,
760 'trans_items': trans_items,
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +0100761 'parent_doctype_name': frm.doc.name,
762 'child_docname': child_docname
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800763 },
764 callback: function() {
765 frm.reload_doc();
766 }
767 });
768 this.hide();
769 refresh_field("items");
770 },
771 primary_action_label: __('Update')
Deepesh Garg40772542023-07-22 23:07:18 +0530772 })
773
774 dialog.show();
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800775}
776
ruthra kumar5981c7e2023-08-29 13:19:26 +0530777
ruthra kumar5981c7e2023-08-29 13:19:26 +0530778
ruthra kumar5981c7e2023-08-29 13:19:26 +0530779
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530780erpnext.utils.map_current_doc = function(opts) {
Sagar Vora78777d62021-03-09 20:35:08 +0530781 function _map() {
Rushabh Mehta55ea7b12016-07-15 16:43:25 +0530782 if($.isArray(cur_frm.doc.items) && cur_frm.doc.items.length > 0) {
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530783 // remove first item row if empty
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530784 if(!cur_frm.doc.items[0].item_code) {
785 cur_frm.doc.items = cur_frm.doc.items.splice(1);
786 }
bhupen3c7e70f2016-11-30 14:32:11 +0530787
788 // find the doctype of the items table
789 var items_doctype = frappe.meta.get_docfield(cur_frm.doctype, 'items').options;
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530790
bhupen3c7e70f2016-11-30 14:32:11 +0530791 // find the link fieldname from items table for the given
792 // source_doctype
793 var link_fieldname = null;
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530794 frappe.get_meta(items_doctype).fields.forEach(function(d) {
bhupen3c7e70f2016-11-30 14:32:11 +0530795 if(d.options===opts.source_doctype) link_fieldname = d.fieldname; });
796
Nabin Hait802b4352017-01-09 15:32:20 +0530797 // search in existing items if the source_name is already set and full qty fetched
bhupen3c7e70f2016-11-30 14:32:11 +0530798 var already_set = false;
Nabin Hait802b4352017-01-09 15:32:20 +0530799 var item_qty_map = {};
bhupen3c7e70f2016-11-30 14:32:11 +0530800
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530801 $.each(cur_frm.doc.items, function(i, d) {
802 opts.source_name.forEach(function(src) {
803 if(d[link_fieldname]==src) {
804 already_set = true;
805 if (item_qty_map[d.item_code])
806 item_qty_map[d.item_code] += flt(d.qty);
807 else
808 item_qty_map[d.item_code] = flt(d.qty);
809 }
810 });
811 });
812
813 if(already_set) {
814 opts.source_name.forEach(function(src) {
815 frappe.model.with_doc(opts.source_doctype, src, function(r) {
816 var source_doc = frappe.model.get_doc(opts.source_doctype, src);
817 $.each(source_doc.items || [], function(i, row) {
818 if(row.qty > flt(item_qty_map[row.item_code])) {
819 already_set = false;
820 return false;
821 }
822 })
823 })
824
825 if(already_set) {
826 frappe.msgprint(__("You have already selected items from {0} {1}",
827 [opts.source_doctype, src]));
828 return;
829 }
830
831 })
Nabin Hait802b4352017-01-09 15:32:20 +0530832 }
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530833 }
834
835 return frappe.call({
836 // Sometimes we hit the limit for URL length of a GET request
837 // as we send the full target_doc. Hence this is a POST request.
838 type: "POST",
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530839 method: 'frappe.model.mapper.map_docs',
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530840 args: {
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530841 "method": opts.method,
842 "source_names": opts.source_name,
843 "target_doc": cur_frm.doc,
Maricadb002702020-02-17 15:58:08 +0530844 "args": opts.args
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530845 },
s-aga-r2d8363a2023-09-02 11:02:24 +0530846 freeze: true,
847 freeze_message: __("Mapping {0} ...", [opts.source_doctype]),
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530848 callback: function(r) {
849 if(!r.exc) {
Deepesh Garg9b1c2222023-12-27 22:37:01 +0530850 frappe.model.sync(r.message);
Vishal Dhayagudef06c2812017-12-26 16:22:40 +0530851 cur_frm.dirty();
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530852 cur_frm.refresh();
853 }
854 }
855 });
856 }
Sagar Vora78777d62021-03-09 20:35:08 +0530857
858 let query_args = {};
859 if (opts.get_query_filters) {
860 query_args.filters = opts.get_query_filters;
861 }
862
863 if (opts.get_query_method) {
864 query_args.query = opts.get_query_method;
865 }
866
867 if (query_args.filters || query_args.query) {
868 opts.get_query = () => query_args;
869 }
870
871 if (opts.source_doctype) {
ruthra kumar7da9ffa2024-01-03 17:59:15 +0530872 let data_fields = [];
873 if(opts.source_doctype == "Purchase Receipt") {
874 data_fields.push({
875 fieldname: 'merge_taxes',
876 fieldtype: 'Check',
877 label: __('Merge taxes from multiple documents'),
878 });
879 }
Sagar Vora78777d62021-03-09 20:35:08 +0530880 const d = new frappe.ui.form.MultiSelectDialog({
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530881 doctype: opts.source_doctype,
882 target: opts.target,
883 date_field: opts.date_field || undefined,
884 setters: opts.setters,
ruthra kumar7da9ffa2024-01-03 17:59:15 +0530885 data_fields: data_fields,
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530886 get_query: opts.get_query,
marination4f395cc2020-09-24 12:43:41 +0530887 add_filters_group: 1,
Saqib7292f542021-09-13 12:13:43 +0530888 allow_child_item_selection: opts.allow_child_item_selection,
gn3060292a619fd2022-06-29 17:15:21 +0800889 child_fieldname: opts.child_fieldname,
Saqib7292f542021-09-13 12:13:43 +0530890 child_columns: opts.child_columns,
Rohit Waghchaure69ffddf2021-10-07 17:33:58 +0530891 size: opts.size,
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530892 action: function(selections, args) {
893 let values = selections;
Saqibe03d9aa2021-09-17 13:03:27 +0530894 if (values.length === 0) {
Nabin Haita11dcb62017-12-04 13:36:50 +0530895 frappe.msgprint(__("Please select {0}", [opts.source_doctype]))
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530896 return;
897 }
898 opts.source_name = values;
ruthra kumar7da9ffa2024-01-03 17:59:15 +0530899 if (opts.allow_child_item_selection || opts.source_doctype == "Purchase Receipt") {
900 // args contains filtered child docnames
901 opts.args = args;
902 }
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530903 d.dialog.hide();
904 _map();
905 },
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530906 });
Sagar Vora78777d62021-03-09 20:35:08 +0530907
908 return d;
909 }
910
911 if (opts.source_name) {
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530912 opts.source_name = [opts.source_name];
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530913 _map();
914 }
915}
916
Rushabh Mehta180e4352016-07-26 17:57:42 +0530917frappe.form.link_formatters['Item'] = function(value, doc) {
Alan157b3882021-04-21 21:00:22 +0530918 if (doc && value && doc.item_name && doc.item_name !== value && doc.item_code === value) {
marination824f48f2020-10-12 20:08:03 +0530919 return value + ': ' + doc.item_name;
920 } else if (!value && doc.doctype && doc.item_name) {
921 // format blank value in child table
922 return doc.item_name;
Rushabh Mehta180e4352016-07-26 17:57:42 +0530923 } else {
marination824f48f2020-10-12 20:08:03 +0530924 // if value is blank in report view or item code and name are the same, return as is
Rushabh Mehta180e4352016-07-26 17:57:42 +0530925 return value;
926 }
927}
928
929frappe.form.link_formatters['Employee'] = function(value, doc) {
Rucha Mahabal5ba1bc12021-11-23 09:30:30 +0530930 if (doc && value && doc.employee_name && doc.employee_name !== value && doc.employee === value) {
931 return value + ': ' + doc.employee_name;
932 } else if (!value && doc.doctype && doc.employee_name) {
933 // format blank value in child table
934 return doc.employee;
Rushabh Mehta180e4352016-07-26 17:57:42 +0530935 } else {
Rucha Mahabal5ba1bc12021-11-23 09:30:30 +0530936 // if value is blank in report view or project name and name are the same, return as is
Rushabh Mehta180e4352016-07-26 17:57:42 +0530937 return value;
938 }
939}
940
Rucha Mahabal59961f72021-05-20 23:43:19 +0530941frappe.form.link_formatters['Project'] = function(value, doc) {
942 if (doc && value && doc.project_name && doc.project_name !== value && doc.project === value) {
943 return value + ': ' + doc.project_name;
944 } else if (!value && doc.doctype && doc.project_name) {
945 // format blank value in child table
946 return doc.project;
947 } else {
948 // if value is blank in report view or project name and name are the same, return as is
949 return value;
950 }
951};
952
Rushabh Mehta95b995b2015-05-28 12:10:55 +0530953// add description on posting time
954$(document).on('app_ready', function() {
955 if(!frappe.datetime.is_timezone_same()) {
956 $.each(["Stock Reconciliation", "Stock Entry", "Stock Ledger Entry",
957 "Delivery Note", "Purchase Receipt", "Sales Invoice"], function(i, d) {
958 frappe.ui.form.on(d, "onload", function(frm) {
959 cur_frm.set_df_property("posting_time", "description",
Faris Ansariab74ca72017-05-30 12:54:42 +0530960 frappe.sys_defaults.time_zone);
Rushabh Mehta95b995b2015-05-28 12:10:55 +0530961 });
962 });
963 }
akshay14384c22016-07-28 13:53:17 +0530964});
Alanc6dc9ea2021-05-07 20:30:04 +0530965
Himanshuec25d592021-06-14 19:05:52 +0530966// Show SLA dashboard
967$(document).on('app_ready', function() {
Ankush Menatbd9ef742023-07-16 11:34:42 +0530968 $.each(frappe.boot.service_level_agreement_doctypes, function(_i, d) {
969 frappe.ui.form.on(d, {
970 onload: function(frm) {
971 if (!frm.doc.service_level_agreement)
972 return;
Himanshuec25d592021-06-14 19:05:52 +0530973
Ankush Menatbd9ef742023-07-16 11:34:42 +0530974 frappe.call({
975 method: 'erpnext.support.doctype.service_level_agreement.service_level_agreement.get_service_level_agreement_filters',
976 args: {
977 doctype: frm.doc.doctype,
978 name: frm.doc.service_level_agreement,
979 customer: frm.doc.customer
Himanshuec25d592021-06-14 19:05:52 +0530980 },
Ankush Menatbd9ef742023-07-16 11:34:42 +0530981 callback: function (r) {
982 if (r && r.message) {
983 frm.set_query('priority', function() {
984 return {
985 filters: {
986 'name': ['in', r.message.priority],
Himanshuec25d592021-06-14 19:05:52 +0530987 }
Ankush Menatbd9ef742023-07-16 11:34:42 +0530988 };
Himanshuec25d592021-06-14 19:05:52 +0530989 });
Ankush Menatbd9ef742023-07-16 11:34:42 +0530990 frm.set_query('service_level_agreement', function() {
991 return {
992 filters: {
993 'name': ['in', r.message.service_level_agreements],
994 }
995 };
996 });
Himanshuec25d592021-06-14 19:05:52 +0530997 }
Ankush Menatbd9ef742023-07-16 11:34:42 +0530998 }
Himanshuec25d592021-06-14 19:05:52 +0530999 });
Ankush Menatbd9ef742023-07-16 11:34:42 +05301000 },
1001
1002 refresh: function(frm) {
1003 if (frm.doc.status !== 'Closed' && frm.doc.service_level_agreement
1004 && ['First Response Due', 'Resolution Due'].includes(frm.doc.agreement_status)) {
1005 frappe.call({
1006 'method': 'frappe.client.get',
1007 args: {
1008 doctype: 'Service Level Agreement',
1009 name: frm.doc.service_level_agreement
1010 },
1011 callback: function(data) {
1012 let statuses = data.message.pause_sla_on;
1013 const hold_statuses = [];
1014 $.each(statuses, (_i, entry) => {
1015 hold_statuses.push(entry.status);
1016 });
1017 if (hold_statuses.includes(frm.doc.status)) {
1018 frm.dashboard.clear_headline();
1019 let message = {'indicator': 'orange', 'msg': __('SLA is on hold since {0}', [moment(frm.doc.on_hold_since).fromNow(true)])};
1020 frm.dashboard.set_headline_alert(
1021 '<div class="row">' +
1022 '<div class="col-xs-12">' +
1023 '<span class="indicator whitespace-nowrap '+ message.indicator +'"><span>'+ message.msg +'</span></span> ' +
1024 '</div>' +
1025 '</div>'
1026 );
1027 } else {
1028 set_time_to_resolve_and_response(frm, data.message.apply_sla_for_resolution);
1029 }
1030 }
1031 });
1032 } else if (frm.doc.service_level_agreement) {
1033 frm.dashboard.clear_headline();
1034
1035 let agreement_status = (frm.doc.agreement_status == 'Fulfilled') ?
1036 {'indicator': 'green', 'msg': 'Service Level Agreement has been fulfilled'} :
1037 {'indicator': 'red', 'msg': 'Service Level Agreement Failed'};
1038
1039 frm.dashboard.set_headline_alert(
1040 '<div class="row">' +
1041 '<div class="col-xs-12">' +
1042 '<span class="indicator whitespace-nowrap '+ agreement_status.indicator +'"><span class="hidden-xs">'+ agreement_status.msg +'</span></span> ' +
1043 '</div>' +
1044 '</div>'
1045 );
1046 }
1047 },
1048 });
Himanshuec25d592021-06-14 19:05:52 +05301049 });
1050});
1051
1052function set_time_to_resolve_and_response(frm, apply_sla_for_resolution) {
1053 frm.dashboard.clear_headline();
1054
Saqib24114772021-12-15 11:45:34 +05301055 let time_to_respond;
Saqib Ansari476e81a2021-12-06 18:55:30 +05301056 if (!frm.doc.first_responded_on) {
Himanshuec25d592021-06-14 19:05:52 +05301057 time_to_respond = get_time_left(frm.doc.response_by, frm.doc.agreement_status);
Saqib24114772021-12-15 11:45:34 +05301058 } else {
1059 time_to_respond = get_status(frm.doc.response_by, frm.doc.first_responded_on);
Himanshuec25d592021-06-14 19:05:52 +05301060 }
1061
1062 let alert = `
1063 <div class="row">
1064 <div class="col-xs-12 col-sm-6">
1065 <span class="indicator whitespace-nowrap ${time_to_respond.indicator}">
1066 <span>Time to Respond: ${time_to_respond.diff_display}</span>
1067 </span>
1068 </div>`;
1069
1070
1071 if (apply_sla_for_resolution) {
Saqib24114772021-12-15 11:45:34 +05301072 let time_to_resolve;
Saqib Ansari476e81a2021-12-06 18:55:30 +05301073 if (!frm.doc.resolution_date) {
Himanshuec25d592021-06-14 19:05:52 +05301074 time_to_resolve = get_time_left(frm.doc.resolution_by, frm.doc.agreement_status);
Saqib24114772021-12-15 11:45:34 +05301075 } else {
1076 time_to_resolve = get_status(frm.doc.resolution_by, frm.doc.resolution_date);
Himanshuec25d592021-06-14 19:05:52 +05301077 }
1078
1079 alert += `
1080 <div class="col-xs-12 col-sm-6">
1081 <span class="indicator whitespace-nowrap ${time_to_resolve.indicator}">
1082 <span>Time to Resolve: ${time_to_resolve.diff_display}</span>
1083 </span>
1084 </div>`;
1085 }
1086
1087 alert += '</div>';
1088
1089 frm.dashboard.set_headline_alert(alert);
1090}
1091
1092function get_time_left(timestamp, agreement_status) {
Ankush Menateaf86a62023-12-14 15:53:57 +05301093 const diff = moment(timestamp).diff(frappe.datetime.system_datetime(true));
Himanshuec25d592021-06-14 19:05:52 +05301094 const diff_display = diff >= 44500 ? moment.duration(diff).humanize() : 'Failed';
1095 let indicator = (diff_display == 'Failed' && agreement_status != 'Fulfilled') ? 'red' : 'green';
1096 return {'diff_display': diff_display, 'indicator': indicator};
1097}
1098
Saqib24114772021-12-15 11:45:34 +05301099function get_status(expected, actual) {
1100 const time_left = moment(expected).diff(moment(actual));
Saqib Ansari476e81a2021-12-06 18:55:30 +05301101 if (time_left >= 0) {
Himanshuec25d592021-06-14 19:05:52 +05301102 return {'diff_display': 'Fulfilled', 'indicator': 'green'};
1103 } else {
1104 return {'diff_display': 'Failed', 'indicator': 'red'};
1105 }
1106}
1107
Alanc6dc9ea2021-05-07 20:30:04 +05301108function attach_selector_button(inner_text, append_loction, context, grid_row) {
1109 let $btn_div = $("<div>").css({"margin-bottom": "10px", "margin-top": "10px"})
1110 .appendTo(append_loction);
1111 let $btn = $(`<button class="btn btn-sm btn-default">${inner_text}</button>`)
1112 .appendTo($btn_div);
1113
1114 $btn.on("click", function() {
1115 context.show_serial_batch_selector(grid_row.frm, grid_row.doc, "", "", true);
1116 });
ruthra kumar5981c7e2023-08-29 13:19:26 +05301117}