blob: d435711cf52ab6b47d032e1f9dc08e471f750c35 [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)
Rushabh Mehta66d52b52014-03-27 14:17:33 +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() {
Rushabh Mehtac38fc712014-04-16 17:21:25 +053024 if(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
Anand Doshibdee6e02013-07-09 13:03:39 +053029 hide_company: function() {
30 if(cur_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) {
33 if(!cur_frm.doc.company) cur_frm.set_value("company", companies[0]);
34 cur_frm.toggle_display("company", false);
Rushabh Mehta45ca8a42015-04-28 16:02:09 +053035 } else if(erpnext.last_selected_company) {
36 if(!cur_frm.doc.company) cur_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) {
43 return frappe.get_doc(":Company", company).enable_perpetual_inventory
44 }
45 },
46
Makarand Bauskare6712c12017-10-25 12:17:40 +053047 stale_rate_allowed: () => {
rohitwaghchaure7677ff02017-11-02 18:12:14 +053048 return cint(frappe.boot.sysdefaults.allow_stale);
Makarand Bauskare6712c12017-10-25 12:17:40 +053049 },
50
Alanc6dc9ea2021-05-07 20:30:04 +053051 setup_serial_or_batch_no: function() {
52 let grid_row = cur_frm.open_grid_row();
53 if (!grid_row || !grid_row.grid_form.fields_dict.serial_no ||
54 grid_row.grid_form.fields_dict.serial_no.get_status() !== "Write") return;
Rushabh Mehtac38fc712014-04-16 17:21:25 +053055
Alanc6dc9ea2021-05-07 20:30:04 +053056 frappe.model.get_value('Item', {'name': grid_row.doc.item_code},
57 ['has_serial_no', 'has_batch_no'], ({has_serial_no, has_batch_no}) => {
58 Object.assign(grid_row.doc, {has_serial_no, has_batch_no});
Rushabh Mehtac38fc712014-04-16 17:21:25 +053059
Alanc6dc9ea2021-05-07 20:30:04 +053060 if (has_serial_no) {
61 attach_selector_button(__("Add Serial No"),
62 grid_row.grid_form.fields_dict.serial_no.$wrapper, this, grid_row);
63 } else if (has_batch_no) {
64 attach_selector_button(__("Pick Batch No"),
65 grid_row.grid_form.fields_dict.batch_no.$wrapper, this, grid_row);
Marica29a2e162019-11-12 14:43:41 +053066 }
Alanc6dc9ea2021-05-07 20:30:04 +053067 }
68 );
deepeshgarg007e64c3572019-05-14 08:50:45 +053069 },
Nabin Hait1ed1c4e2019-11-25 12:33:40 +053070
71 route_to_adjustment_jv: (args) => {
72 frappe.model.with_doctype('Journal Entry', () => {
73 // route to adjustment Journal Entry to handle Account Balance and Stock Value mismatch
74 let journal_entry = frappe.model.get_new_doc('Journal Entry');
75
76 args.accounts.forEach((je_account) => {
77 let child_row = frappe.model.add_child(journal_entry, "accounts");
78 child_row.account = je_account.account;
79 child_row.debit_in_account_currency = je_account.debit_in_account_currency;
80 child_row.credit_in_account_currency = je_account.credit_in_account_currency;
81 child_row.party_type = "" ;
82 });
83 frappe.set_route('Form','Journal Entry', journal_entry.name);
84 });
Frappe PR Bot255b99e2021-08-24 20:19:22 +053085 },
86
Ankush Menatd37541d2021-12-10 12:04:10 +053087 route_to_pending_reposts: (args) => {
88 frappe.set_route('List', 'Repost Item Valuation', args);
89 },
Rushabh Mehtac38fc712014-04-16 17:21:25 +053090});
Rushabh Mehta7d368752014-11-24 14:16:47 +053091
Nabin Haitb072c742014-12-16 12:49:13 +053092
93$.extend(erpnext.utils, {
Rushabh Mehta559aa3a2016-09-19 16:04:58 +053094 set_party_dashboard_indicators: function(frm) {
95 if(frm.doc.__onload && frm.doc.__onload.dashboard_info) {
deepeshgarg007920dc142018-11-23 10:17:28 +053096 var company_wise_info = frm.doc.__onload.dashboard_info;
deepeshgarg007f31caff2018-11-27 15:04:12 +053097 if(company_wise_info.length > 1) {
deepeshgarg007a1cffc32018-11-23 16:51:35 +053098 company_wise_info.forEach(function(info) {
deepeshgarg00712f5cef2018-12-25 16:06:19 +053099 erpnext.utils.add_indicator_for_multicompany(frm, info);
deepeshgarg007a1cffc32018-11-23 16:51:35 +0530100 });
deepeshgarg00712f5cef2018-12-25 16:06:19 +0530101 } else if (company_wise_info.length === 1) {
deepeshgarg00764238ee2018-12-25 16:28:39 +0530102 frm.dashboard.add_indicator(__('Annual Billing: {0}',
103 [format_currency(company_wise_info[0].billing_this_year, company_wise_info[0].currency)]), 'blue');
104 frm.dashboard.add_indicator(__('Total Unpaid: {0}',
105 [format_currency(company_wise_info[0].total_unpaid, company_wise_info[0].currency)]),
deepeshgarg0078300f5e2019-01-01 20:28:49 +0530106 company_wise_info[0].total_unpaid ? 'orange' : 'green');
deepeshgarg00712f5cef2018-12-25 16:06:19 +0530107
deepeshgarg00764238ee2018-12-25 16:28:39 +0530108 if(company_wise_info[0].loyalty_points) {
109 frm.dashboard.add_indicator(__('Loyalty Points: {0}',
110 [company_wise_info[0].loyalty_points]), 'blue');
111 }
deepeshgarg007f31caff2018-11-27 15:04:12 +0530112 }
Rushabh Mehta559aa3a2016-09-19 16:04:58 +0530113 }
114 },
115
Rohit Waghchaure708eefb2023-07-10 16:54:55 +0530116 view_serial_batch_nos: function(frm) {
rohitwaghchaure3c15fea2023-08-24 17:24:44 +0530117 if (!frm.doc?.items) {
118 return;
119 }
120
Rohit Waghchaure708eefb2023-07-10 16:54:55 +0530121 let bundle_ids = frm.doc.items.filter(d => d.serial_and_batch_bundle);
122
123 if (bundle_ids?.length) {
124 frm.add_custom_button(__('Serial / Batch Nos'), () => {
125 frappe.route_options = {
126 "voucher_no": frm.doc.name,
127 "voucher_type": frm.doc.doctype,
128 "from_date": frm.doc.posting_date || frm.doc.transaction_date,
129 "to_date": frm.doc.posting_date || frm.doc.transaction_date,
130 "company": frm.doc.company,
131 };
132 frappe.set_route("query-report", "Serial and Batch Summary");
133 }, __('View'));
134 }
135 },
136
deepeshgarg00712f5cef2018-12-25 16:06:19 +0530137 add_indicator_for_multicompany: function(frm, info) {
Deepak867f2c62022-05-17 11:52:52 +0530138 frm.dashboard.stats_area.show();
deepeshgarg00712f5cef2018-12-25 16:06:19 +0530139 frm.dashboard.stats_area_row.addClass('flex');
140 frm.dashboard.stats_area_row.css('flex-wrap', 'wrap');
141
142 var color = info.total_unpaid ? 'orange' : 'green';
143
144 var indicator = $('<div class="flex-column col-xs-6">'+
145 '<div style="margin-top:10px"><h6>'+info.company+'</h6></div>'+
146
147 '<div class="badge-link small" style="margin-bottom:10px"><span class="indicator blue">'+
148 'Annual Billing: '+format_currency(info.billing_this_year, info.currency)+'</span></div>'+
149
150 '<div class="badge-link small" style="margin-bottom:10px">'+
151 '<span class="indicator '+color+'">Total Unpaid: '
152 +format_currency(info.total_unpaid, info.currency)+'</span></div>'+
153
154
155 '</div>').appendTo(frm.dashboard.stats_area_row);
156
157 if(info.loyalty_points){
158 $('<div class="badge-link small" style="margin-bottom:10px"><span class="indicator blue">'+
159 'Loyalty Points: '+info.loyalty_points+'</span></div>').appendTo(indicator);
160 }
161
162 return indicator;
163 },
164
Shreya Shah149f7ee2018-03-27 11:29:25 +0530165 get_party_name: function(party_type) {
166 var dict = {'Customer': 'customer_name', 'Supplier': 'supplier_name', 'Employee': 'employee_name',
167 'Member': 'member_name'};
168 return dict[party_type];
169 },
170
Rushabh Mehta49f97472018-08-30 18:50:48 +0530171 copy_value_in_all_rows: function(doc, dt, dn, table_fieldname, fieldname) {
Neil Trini Lasradofe2ffae2015-07-08 18:16:51 +0530172 var d = locals[dt][dn];
173 if(d[fieldname]){
174 var cl = doc[table_fieldname] || [];
175 for(var i = 0; i < cl.length; i++) {
176 if(!cl[i][fieldname]) cl[i][fieldname] = d[fieldname];
177 }
178 }
179 refresh_field(table_fieldname);
Makarand Bauskar157c3342017-05-26 21:32:33 +0530180 },
181
182 get_terms: function(tc_name, doc, callback) {
183 if(tc_name) {
184 return frappe.call({
185 method: 'erpnext.setup.doctype.terms_and_conditions.terms_and_conditions.get_terms_and_conditions',
186 args: {
187 template_name: tc_name,
188 doc: doc
189 },
190 callback: function(r) {
191 callback(r)
192 }
193 });
194 }
tundebabzy1a947db2017-08-29 13:48:27 +0100195 },
196
rohitwaghchaure713cfc72018-09-11 17:40:37 +0530197 make_bank_account: function(doctype, docname) {
198 frappe.call({
199 method: "erpnext.accounts.doctype.bank_account.bank_account.make_bank_account",
200 args: {
201 doctype: doctype,
202 docname: docname
203 },
204 freeze: true,
205 callback: function(r) {
206 var doclist = frappe.model.sync(r.message);
207 frappe.set_route("Form", doclist[0].doctype, doclist[0].name);
208 }
209 })
210 },
211
Deepesh Garg11ea0b12020-05-26 19:23:45 +0530212 add_dimensions: function(report_name, index) {
213 let filters = frappe.query_reports[report_name].filters;
214
Deepesh Garg7b2d5182020-12-04 11:28:26 +0530215 frappe.call({
216 method: "erpnext.accounts.doctype.accounting_dimension.accounting_dimension.get_dimensions",
217 callback: function(r) {
218 let accounting_dimensions = r.message[0];
219 accounting_dimensions.forEach((dimension) => {
220 let found = filters.some(el => el.fieldname === dimension['fieldname']);
Deepesh Garg11ea0b12020-05-26 19:23:45 +0530221
Deepesh Garg7b2d5182020-12-04 11:28:26 +0530222 if (!found) {
Deepesh Garg23ab5c52020-12-31 11:29:06 +0530223 filters.splice(index, 0, {
Deepesh Garg7b2d5182020-12-04 11:28:26 +0530224 "fieldname": dimension["fieldname"],
225 "label": __(dimension["label"]),
Rohit Waghchaure69be22b2022-05-14 17:19:34 +0530226 "fieldtype": "MultiSelectList",
227 get_data: function(txt) {
228 return frappe.db.get_link_options(dimension["document_type"], txt);
229 },
Deepesh Garg7b2d5182020-12-04 11:28:26 +0530230 });
231 }
Deepesh Garg11ea0b12020-05-26 19:23:45 +0530232 });
233 }
234 });
235 },
236
Rohit Waghchauredbec5cf2022-06-22 12:24:08 +0530237 add_inventory_dimensions: function(report_name, index) {
238 let filters = frappe.query_reports[report_name].filters;
239
240 frappe.call({
241 method: "erpnext.stock.doctype.inventory_dimension.inventory_dimension.get_inventory_dimensions",
242 callback: function(r) {
243 if (r.message && r.message.length) {
244 r.message.forEach((dimension) => {
Rohit Waghchaure0e388ba2023-02-20 12:20:03 +0530245 let existing_filter = filters.filter(el => el.fieldname === dimension['fieldname']);
Rohit Waghchauredbec5cf2022-06-22 12:24:08 +0530246
Rohit Waghchaure0e388ba2023-02-20 12:20:03 +0530247 if (!existing_filter.length) {
Rohit Waghchauredbec5cf2022-06-22 12:24:08 +0530248 filters.splice(index, 0, {
249 "fieldname": dimension["fieldname"],
Rohit Waghchaureef7def82022-09-07 14:40:18 +0530250 "label": __(dimension["doctype"]),
Rohit Waghchauredbec5cf2022-06-22 12:24:08 +0530251 "fieldtype": "MultiSelectList",
252 get_data: function(txt) {
253 return frappe.db.get_link_options(dimension["doctype"], txt);
254 },
255 });
Rohit Waghchaure0e388ba2023-02-20 12:20:03 +0530256 } else {
257 existing_filter[0]['fieldtype'] = "MultiSelectList";
258 existing_filter[0]['get_data'] = function(txt) {
259 return frappe.db.get_link_options(dimension["doctype"], txt);
260 }
Rohit Waghchauredbec5cf2022-06-22 12:24:08 +0530261 }
262 });
263 }
264 }
265 });
266 },
267
rohitwaghchaure166b78f2017-09-07 16:14:22 +0530268 make_subscription: function(doctype, docname) {
269 frappe.call({
Rucha Mahabal65a627c2019-07-17 13:50:32 +0530270 method: "frappe.automation.doctype.auto_repeat.auto_repeat.make_auto_repeat",
rohitwaghchaure166b78f2017-09-07 16:14:22 +0530271 args: {
272 doctype: doctype,
273 docname: docname
274 },
275 callback: function(r) {
276 var doclist = frappe.model.sync(r.message);
277 frappe.set_route("Form", doclist[0].doctype, doclist[0].name);
278 }
279 })
280 },
281
Saif90cf2dd2018-09-30 21:46:31 +0500282 make_pricing_rule: function(doctype, docname) {
283 frappe.call({
284 method: "erpnext.accounts.doctype.pricing_rule.pricing_rule.make_pricing_rule",
285 args: {
286 doctype: doctype,
287 docname: docname
288 },
289 callback: function(r) {
290 var doclist = frappe.model.sync(r.message);
291 frappe.set_route("Form", doclist[0].doctype, doclist[0].name);
292 }
293 })
294 },
295
tundebabzy1a947db2017-08-29 13:48:27 +0100296 /**
297 * Checks if the first row of a given child table is empty
298 * @param child_table - Child table Doctype
299 * @return {Boolean}
300 **/
301 first_row_is_empty: function(child_table){
302 if($.isArray(child_table) && child_table.length > 0) {
303 return !child_table[0].item_code;
304 }
305 return false;
306 },
307
308 /**
309 * Removes the first row of a child table if it is empty
310 * @param {_Frm} frm - The current form
311 * @param {String} child_table_name - The child table field name
312 * @return {Boolean}
313 **/
314 remove_empty_first_row: function(frm, child_table_name){
315 const rows = frm['doc'][child_table_name];
316 if (this.first_row_is_empty(rows)){
317 frm['doc'][child_table_name] = rows.splice(1);
318 }
319 return rows;
320 },
Zarrar6ffdf942018-06-14 12:24:16 +0530321 get_tree_options: function(option) {
322 // get valid options for tree based on user permission & locals dict
323 let unscrub_option = frappe.model.unscrub(option);
324 let user_permission = frappe.defaults.get_user_permissions();
deepeshgarg0070d64d622019-02-20 17:55:14 +0530325 let options;
326
Zarrar6ffdf942018-06-14 12:24:16 +0530327 if(user_permission && user_permission[unscrub_option]) {
deepeshgarg0070d64d622019-02-20 17:55:14 +0530328 options = user_permission[unscrub_option].map(perm => perm.doc);
Zarrar6ffdf942018-06-14 12:24:16 +0530329 } else {
deepeshgarg0070d64d622019-02-20 17:55:14 +0530330 options = $.map(locals[`:${unscrub_option}`], function(c) { return c.name; }).sort();
Zarrar6ffdf942018-06-14 12:24:16 +0530331 }
deepeshgarg0070d64d622019-02-20 17:55:14 +0530332
333 // filter unique values, as there may be multiple user permissions for any value
334 return options.filter((value, index, self) => self.indexOf(value) === index);
Zarrar6ffdf942018-06-14 12:24:16 +0530335 },
336 get_tree_default: function(option) {
337 // set default for a field based on user permission
338 let options = this.get_tree_options(option);
339 if(options.includes(frappe.defaults.get_default(option))) {
340 return frappe.defaults.get_default(option);
341 } else {
342 return options[0];
343 }
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400344 },
Andy Zhubffe9332021-04-12 22:49:26 +1200345 overrides_parent_value_in_all_rows: function(doc, dt, dn, table_fieldname, fieldname, parent_fieldname) {
Marica24e45162021-04-14 18:53:15 +0530346 if (doc[parent_fieldname]) {
Andy Zhubffe9332021-04-12 22:49:26 +1200347 let cl = doc[table_fieldname] || [];
Marica24e45162021-04-14 18:53:15 +0530348 for (let i = 0; i < cl.length; i++) {
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400349 cl[i][fieldname] = doc[parent_fieldname];
350 }
Andy Zhubffe9332021-04-12 22:49:26 +1200351 frappe.refresh_field(table_fieldname);
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400352 }
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400353 },
Nabin Hait34c551d2019-07-03 10:34:31 +0530354 create_new_doc: function (doctype, update_fields) {
355 frappe.model.with_doctype(doctype, function() {
356 var new_doc = frappe.model.get_new_doc(doctype);
357 for (let [key, value] of Object.entries(update_fields)) {
358 new_doc[key] = value;
359 }
360 frappe.ui.form.make_quick_entry(doctype, null, null, new_doc);
361 });
Ankush Menat0b86b1b2022-12-08 16:40:13 +0530362 },
Nabin Hait34c551d2019-07-03 10:34:31 +0530363
Ankush Menat0b86b1b2022-12-08 16:40:13 +0530364 // check if payments app is installed on site, if not warn user.
365 check_payments_app: () => {
366 if (frappe.boot.versions && !frappe.boot.versions.payments) {
367 const marketplace_link = '<a href="https://frappecloud.com/marketplace/apps/payments">Marketplace</a>'
368 const github_link = '<a href="https://github.com/frappe/payments/">GitHub</a>'
369 const msg = __("payments app is not installed. Please install it from {0} or {1}", [marketplace_link, github_link])
370 frappe.msgprint(msg);
371 }
372
373 },
Rohit Waghchaure1c2fe082023-06-15 12:54:43 +0530374
375 pick_serial_and_batch_bundle(frm, cdt, cdn, type_of_transaction, warehouse_field) {
376 let item_row = frappe.get_doc(cdt, cdn);
377 item_row.type_of_transaction = type_of_transaction;
378
379 frappe.db.get_value("Item", item_row.item_code, ["has_batch_no", "has_serial_no"])
380 .then((r) => {
381 item_row.has_batch_no = r.message.has_batch_no;
382 item_row.has_serial_no = r.message.has_serial_no;
383
384 frappe.require("assets/erpnext/js/utils/serial_no_batch_selector.js", function() {
385 new erpnext.SerialBatchPackageSelector(frm, item_row, (r) => {
386 if (r) {
387 let update_values = {
388 "serial_and_batch_bundle": r.name,
389 "qty": Math.abs(r.total_qty)
390 }
391
392 if (!warehouse_field) {
393 warehouse_field = "warehouse";
394 }
395
396 if (r.warehouse) {
397 update_values[warehouse_field] = r.warehouse;
398 }
399
400 frappe.model.set_value(item_row.doctype, item_row.name, update_values);
401 }
402 });
403 });
404 });
Deepesh Garg62706072023-07-16 12:58:42 +0530405 },
406
Deepesh Garg23410612023-07-27 21:03:32 +0530407 get_fiscal_year: function(date, with_dates=false) {
Deepesh Garg3759a412023-07-19 13:17:12 +0530408 if(!date) {
409 date = frappe.datetime.get_today();
410 }
411
Deepesh Garg62706072023-07-16 12:58:42 +0530412 let fiscal_year = '';
413 frappe.call({
414 method: "erpnext.accounts.utils.get_fiscal_year",
415 args: {
416 date: date
417 },
418 async: false,
419 callback: function(r) {
420 if (r.message) {
Deepesh Garg4496a672023-07-24 11:58:16 +0530421 if (with_dates)
422 fiscal_year = r.message;
423 else
424 fiscal_year = r.message[0];
Deepesh Garg62706072023-07-16 12:58:42 +0530425 }
426 }
427 });
428 return fiscal_year;
Rohit Waghchaure1c2fe082023-06-15 12:54:43 +0530429 }
Rushabh Mehta95b995b2015-05-28 12:10:55 +0530430});
431
rohitwaghchaurea3c3dec2018-03-28 11:51:44 +0530432erpnext.utils.select_alternate_items = function(opts) {
433 const frm = opts.frm;
434 const warehouse_field = opts.warehouse_field || 'warehouse';
435 const item_field = opts.item_field || 'item_code';
436
437 this.data = [];
438 const dialog = new frappe.ui.Dialog({
439 title: __("Select Alternate Item"),
440 fields: [
441 {fieldtype:'Section Break', label: __('Items')},
442 {
443 fieldname: "alternative_items", fieldtype: "Table", cannot_add_rows: true,
444 in_place_edit: true, data: this.data,
445 get_data: () => {
446 return this.data;
447 },
448 fields: [{
449 fieldtype:'Data',
450 fieldname:"docname",
451 hidden: 1
452 }, {
453 fieldtype:'Link',
454 fieldname:"item_code",
455 options: 'Item',
456 in_list_view: 1,
457 read_only: 1,
458 label: __('Item Code')
459 }, {
460 fieldtype:'Link',
461 fieldname:"alternate_item",
462 options: 'Item',
463 default: "",
464 in_list_view: 1,
465 label: __('Alternate Item'),
466 onchange: function() {
467 const item_code = this.get_value();
468 const warehouse = this.grid_row.on_grid_fields_dict.warehouse.get_value();
469 if (item_code && warehouse) {
470 frappe.call({
471 method: "erpnext.stock.utils.get_latest_stock_qty",
472 args: {
473 item_code: item_code,
474 warehouse: warehouse
475 },
476 callback: (r) => {
477 this.grid_row.on_grid_fields_dict
478 .actual_qty.set_value(r.message || 0);
479 }
480 })
481 }
482 },
483 get_query: (e) => {
484 return {
485 query: "erpnext.stock.doctype.item_alternative.item_alternative.get_alternative_items",
486 filters: {
487 item_code: e.item_code
488 }
489 };
490 }
491 }, {
492 fieldtype:'Link',
493 fieldname:"warehouse",
494 options: 'Warehouse',
495 default: "",
496 in_list_view: 1,
497 label: __('Warehouse'),
498 onchange: function() {
499 const warehouse = this.get_value();
500 const item_code = this.grid_row.on_grid_fields_dict.item_code.get_value();
501 if (item_code && warehouse) {
502 frappe.call({
503 method: "erpnext.stock.utils.get_latest_stock_qty",
504 args: {
505 item_code: item_code,
506 warehouse: warehouse
507 },
508 callback: (r) => {
509 this.grid_row.on_grid_fields_dict
510 .actual_qty.set_value(r.message || 0);
511 }
512 })
513 }
514 },
515 }, {
516 fieldtype:'Float',
517 fieldname:"actual_qty",
518 default: 0,
519 read_only: 1,
520 in_list_view: 1,
521 label: __('Available Qty')
522 }]
523 },
524 ],
525 primary_action: function() {
526 const args = this.get_values()["alternative_items"];
527 const alternative_items = args.filter(d => {
528 if (d.alternate_item && d.item_code != d.alternate_item) {
529 return true;
530 }
531 });
532
533 alternative_items.forEach(d => {
534 let row = frappe.get_doc(opts.child_doctype, d.docname);
Doridel Cahanape42192b2018-05-16 13:28:39 +0800535 let qty = null;
536 if (row.doctype === 'Work Order Item') {
537 qty = row.required_qty;
538 } else {
539 qty = row.qty;
540 }
rohitwaghchaurea3c3dec2018-03-28 11:51:44 +0530541 row[item_field] = d.alternate_item;
mergify[bot]c1a0f642021-12-17 19:06:19 +0530542 frappe.model.set_value(row.doctype, row.name, 'qty', qty);
543 frappe.model.set_value(row.doctype, row.name, opts.original_item_field, d.item_code);
544 frm.trigger(item_field, row.doctype, row.name);
rohitwaghchaurea3c3dec2018-03-28 11:51:44 +0530545 });
546
547 refresh_field(opts.child_docname);
548 this.hide();
549 },
550 primary_action_label: __('Update')
551 });
552
553 frm.doc[opts.child_docname].forEach(d => {
554 if (!opts.condition || opts.condition(d)) {
555 dialog.fields_dict.alternative_items.df.data.push({
556 "docname": d.name,
557 "item_code": d[item_field],
558 "warehouse": d[warehouse_field],
559 "actual_qty": d.actual_qty
560 });
561 }
562 })
563
564 this.data = dialog.fields_dict.alternative_items.df.data;
565 dialog.fields_dict.alternative_items.grid.refresh();
566 dialog.show();
567}
568
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800569erpnext.utils.update_child_items = function(opts) {
570 const frm = opts.frm;
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +0100571 const cannot_add_row = (typeof opts.cannot_add_row === 'undefined') ? true : opts.cannot_add_row;
572 const child_docname = (typeof opts.cannot_add_row === 'undefined') ? "items" : opts.child_docname;
Saqib56fea7d2020-10-09 21:19:25 +0530573 const child_meta = frappe.get_meta(`${frm.doc.doctype} Item`);
s-aga-r2d8363a2023-09-02 11:02:24 +0530574 const has_reserved_stock = opts.has_reserved_stock ? true : false;
Saqib56fea7d2020-10-09 21:19:25 +0530575 const get_precision = (fieldname) => child_meta.fields.find(f => f.fieldname == fieldname).precision;
576
Devin Slauenwhitea835c1a2023-01-26 16:53:05 -0500577 this.data = frm.doc[opts.child_docname].map((d) => {
578 return {
579 "docname": d.name,
580 "name": d.name,
581 "item_code": d.item_code,
582 "delivery_date": d.delivery_date,
583 "schedule_date": d.schedule_date,
584 "conversion_factor": d.conversion_factor,
585 "qty": d.qty,
586 "rate": d.rate,
s-aga-r9588bb72023-08-21 22:23:57 +0530587 "uom": d.uom,
588 "fg_item": d.fg_item,
589 "fg_item_qty": d.fg_item_qty,
Devin Slauenwhitea835c1a2023-01-26 16:53:05 -0500590 }
591 });
592
Saqib Ansarif53299e2020-04-15 22:08:12 +0530593 const fields = [{
594 fieldtype:'Data',
595 fieldname:"docname",
596 read_only: 1,
597 hidden: 1,
598 }, {
599 fieldtype:'Link',
600 fieldname:"item_code",
601 options: 'Item',
602 in_list_view: 1,
603 read_only: 0,
604 disabled: 0,
Afshandc7280e2021-08-18 17:44:40 +0530605 label: __('Item Code'),
606 get_query: function() {
607 let filters;
608 if (frm.doc.doctype == 'Sales Order') {
609 filters = {"is_sales_item": 1};
610 } else if (frm.doc.doctype == 'Purchase Order') {
Sagar Sharmad074c932022-03-31 19:57:42 +0530611 if (frm.doc.is_subcontracted) {
s-aga-r6d89b2f2022-06-18 15:46:59 +0530612 if (frm.doc.is_old_subcontracting_flow) {
613 filters = {"is_sub_contracted_item": 1};
614 } else {
615 filters = {"is_stock_item": 0};
616 }
Afshandc7280e2021-08-18 17:44:40 +0530617 } else {
618 filters = {"is_purchase_item": 1};
619 }
620 }
621 return {
622 query: "erpnext.controllers.queries.item_query",
623 filters: filters
624 };
625 }
Saqib Ansarif53299e2020-04-15 22:08:12 +0530626 }, {
Saqib61314242020-09-15 11:14:31 +0530627 fieldtype:'Link',
628 fieldname:'uom',
629 options: 'UOM',
630 read_only: 0,
631 label: __('UOM'),
632 reqd: 1,
633 onchange: function () {
634 frappe.call({
635 method: "erpnext.stock.get_item_details.get_conversion_factor",
636 args: { item_code: this.doc.item_code, uom: this.value },
637 callback: r => {
638 if(!r.exc) {
639 if (this.doc.conversion_factor == r.message.conversion_factor) return;
marination4f395cc2020-09-24 12:43:41 +0530640
Saqib61314242020-09-15 11:14:31 +0530641 const docname = this.doc.docname;
642 dialog.fields_dict.trans_items.df.data.some(doc => {
643 if (doc.docname == docname) {
644 doc.conversion_factor = r.message.conversion_factor;
645 dialog.fields_dict.trans_items.grid.refresh();
646 return true;
647 }
648 })
649 }
650 }
651 });
652 }
653 }, {
Saqib Ansarif53299e2020-04-15 22:08:12 +0530654 fieldtype:'Float',
655 fieldname:"qty",
656 default: 0,
657 read_only: 0,
658 in_list_view: 1,
Saqib56fea7d2020-10-09 21:19:25 +0530659 label: __('Qty'),
660 precision: get_precision("qty")
Saqib Ansarif53299e2020-04-15 22:08:12 +0530661 }, {
662 fieldtype:'Currency',
663 fieldname:"rate",
Afshan84184552021-02-24 16:51:11 +0530664 options: "currency",
Saqib Ansarif53299e2020-04-15 22:08:12 +0530665 default: 0,
666 read_only: 0,
667 in_list_view: 1,
Saqib56fea7d2020-10-09 21:19:25 +0530668 label: __('Rate'),
669 precision: get_precision("rate")
Saqib Ansarif53299e2020-04-15 22:08:12 +0530670 }];
671
672 if (frm.doc.doctype == 'Sales Order' || frm.doc.doctype == 'Purchase Order' ) {
673 fields.splice(2, 0, {
674 fieldtype: 'Date',
675 fieldname: frm.doc.doctype == 'Sales Order' ? "delivery_date" : "schedule_date",
676 in_list_view: 1,
Saqib Ansaric579b082020-05-29 22:21:50 +0530677 label: frm.doc.doctype == 'Sales Order' ? __("Delivery Date") : __("Reqd by date"),
678 reqd: 1
Saqib Ansarif53299e2020-04-15 22:08:12 +0530679 })
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +0530680 fields.splice(3, 0, {
681 fieldtype: 'Float',
682 fieldname: "conversion_factor",
Saqib56fea7d2020-10-09 21:19:25 +0530683 label: __("Conversion Factor"),
684 precision: get_precision('conversion_factor')
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +0530685 })
Saqib Ansarif53299e2020-04-15 22:08:12 +0530686 }
687
s-aga-rfaf9f132023-08-21 15:51:57 +0530688 if (frm.doc.doctype == 'Purchase Order' && frm.doc.is_subcontracted && !frm.doc.is_old_subcontracting_flow) {
689 fields.push({
690 fieldtype:'Link',
691 fieldname:'fg_item',
692 options: 'Item',
693 reqd: 1,
694 in_list_view: 0,
695 read_only: 0,
696 disabled: 0,
697 label: __('Finished Good Item'),
698 get_query: () => {
699 return {
700 filters: {
701 'is_stock_item': 1,
702 'is_sub_contracted_item': 1,
703 'default_bom': ['!=', '']
704 }
705 }
706 },
707 }, {
708 fieldtype:'Float',
709 fieldname:'fg_item_qty',
710 reqd: 1,
711 default: 0,
712 read_only: 0,
713 in_list_view: 0,
714 label: __('Finished Good Item Qty'),
715 precision: get_precision('fg_item_qty')
716 })
717 }
718
Deepesh Garg40772542023-07-22 23:07:18 +0530719 let dialog = new frappe.ui.Dialog({
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800720 title: __("Update Items"),
Raffael Meyerd5fe1432023-07-14 08:57:35 +0200721 size: "extra-large",
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800722 fields: [
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800723 {
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +0100724 fieldname: "trans_items",
725 fieldtype: "Table",
Maricafc96c1a2020-03-06 10:57:59 +0530726 label: "Items",
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +0100727 cannot_add_rows: cannot_add_row,
Saqibbc919e22020-11-05 17:38:35 +0530728 in_place_edit: false,
Maricafc96c1a2020-03-06 10:57:59 +0530729 reqd: 1,
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +0100730 data: this.data,
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800731 get_data: () => {
732 return this.data;
733 },
Saqib Ansarif53299e2020-04-15 22:08:12 +0530734 fields: fields
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800735 },
736 ],
737 primary_action: function() {
s-aga-r2d8363a2023-09-02 11:02:24 +0530738 if (frm.doctype == "Sales Order" && has_reserved_stock) {
739 this.hide();
740 frappe.confirm(
741 __('The reserved stock will be released when you update items. Are you certain you wish to proceed?'),
742 () => this.update_items(),
743 )
744 } else {
745 this.update_items();
746 }
747 },
748 update_items: function() {
Ankush Menat6de7b8e2021-08-24 12:18:40 +0530749 const trans_items = this.get_values()["trans_items"].filter((item) => !!item.item_code);
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800750 frappe.call({
751 method: 'erpnext.controllers.accounts_controller.update_child_qty_rate',
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +0100752 freeze: true,
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800753 args: {
754 'parent_doctype': frm.doc.doctype,
755 'trans_items': trans_items,
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +0100756 'parent_doctype_name': frm.doc.name,
757 'child_docname': child_docname
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800758 },
759 callback: function() {
760 frm.reload_doc();
761 }
762 });
763 this.hide();
764 refresh_field("items");
765 },
766 primary_action_label: __('Update')
Deepesh Garg40772542023-07-22 23:07:18 +0530767 })
768
769 dialog.show();
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800770}
771
ruthra kumar5981c7e2023-08-29 13:19:26 +0530772
ruthra kumar5981c7e2023-08-29 13:19:26 +0530773
ruthra kumar5981c7e2023-08-29 13:19:26 +0530774
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530775erpnext.utils.map_current_doc = function(opts) {
Sagar Vora78777d62021-03-09 20:35:08 +0530776 function _map() {
Rushabh Mehta55ea7b12016-07-15 16:43:25 +0530777 if($.isArray(cur_frm.doc.items) && cur_frm.doc.items.length > 0) {
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530778 // remove first item row if empty
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530779 if(!cur_frm.doc.items[0].item_code) {
780 cur_frm.doc.items = cur_frm.doc.items.splice(1);
781 }
bhupen3c7e70f2016-11-30 14:32:11 +0530782
783 // find the doctype of the items table
784 var items_doctype = frappe.meta.get_docfield(cur_frm.doctype, 'items').options;
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530785
bhupen3c7e70f2016-11-30 14:32:11 +0530786 // find the link fieldname from items table for the given
787 // source_doctype
788 var link_fieldname = null;
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530789 frappe.get_meta(items_doctype).fields.forEach(function(d) {
bhupen3c7e70f2016-11-30 14:32:11 +0530790 if(d.options===opts.source_doctype) link_fieldname = d.fieldname; });
791
Nabin Hait802b4352017-01-09 15:32:20 +0530792 // search in existing items if the source_name is already set and full qty fetched
bhupen3c7e70f2016-11-30 14:32:11 +0530793 var already_set = false;
Nabin Hait802b4352017-01-09 15:32:20 +0530794 var item_qty_map = {};
bhupen3c7e70f2016-11-30 14:32:11 +0530795
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530796 $.each(cur_frm.doc.items, function(i, d) {
797 opts.source_name.forEach(function(src) {
798 if(d[link_fieldname]==src) {
799 already_set = true;
800 if (item_qty_map[d.item_code])
801 item_qty_map[d.item_code] += flt(d.qty);
802 else
803 item_qty_map[d.item_code] = flt(d.qty);
804 }
805 });
806 });
807
808 if(already_set) {
809 opts.source_name.forEach(function(src) {
810 frappe.model.with_doc(opts.source_doctype, src, function(r) {
811 var source_doc = frappe.model.get_doc(opts.source_doctype, src);
812 $.each(source_doc.items || [], function(i, row) {
813 if(row.qty > flt(item_qty_map[row.item_code])) {
814 already_set = false;
815 return false;
816 }
817 })
818 })
819
820 if(already_set) {
821 frappe.msgprint(__("You have already selected items from {0} {1}",
822 [opts.source_doctype, src]));
823 return;
824 }
825
826 })
Nabin Hait802b4352017-01-09 15:32:20 +0530827 }
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530828 }
829
830 return frappe.call({
831 // Sometimes we hit the limit for URL length of a GET request
832 // as we send the full target_doc. Hence this is a POST request.
833 type: "POST",
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530834 method: 'frappe.model.mapper.map_docs',
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530835 args: {
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530836 "method": opts.method,
837 "source_names": opts.source_name,
838 "target_doc": cur_frm.doc,
Maricadb002702020-02-17 15:58:08 +0530839 "args": opts.args
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530840 },
s-aga-r2d8363a2023-09-02 11:02:24 +0530841 freeze: true,
842 freeze_message: __("Mapping {0} ...", [opts.source_doctype]),
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530843 callback: function(r) {
844 if(!r.exc) {
845 var doc = frappe.model.sync(r.message);
Vishal Dhayagudef06c2812017-12-26 16:22:40 +0530846 cur_frm.dirty();
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530847 cur_frm.refresh();
848 }
849 }
850 });
851 }
Sagar Vora78777d62021-03-09 20:35:08 +0530852
853 let query_args = {};
854 if (opts.get_query_filters) {
855 query_args.filters = opts.get_query_filters;
856 }
857
858 if (opts.get_query_method) {
859 query_args.query = opts.get_query_method;
860 }
861
862 if (query_args.filters || query_args.query) {
863 opts.get_query = () => query_args;
864 }
865
866 if (opts.source_doctype) {
867 const d = new frappe.ui.form.MultiSelectDialog({
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530868 doctype: opts.source_doctype,
869 target: opts.target,
870 date_field: opts.date_field || undefined,
871 setters: opts.setters,
872 get_query: opts.get_query,
marination4f395cc2020-09-24 12:43:41 +0530873 add_filters_group: 1,
Saqib7292f542021-09-13 12:13:43 +0530874 allow_child_item_selection: opts.allow_child_item_selection,
gn3060292a619fd2022-06-29 17:15:21 +0800875 child_fieldname: opts.child_fieldname,
Saqib7292f542021-09-13 12:13:43 +0530876 child_columns: opts.child_columns,
Rohit Waghchaure69ffddf2021-10-07 17:33:58 +0530877 size: opts.size,
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530878 action: function(selections, args) {
879 let values = selections;
Saqibe03d9aa2021-09-17 13:03:27 +0530880 if (values.length === 0) {
Nabin Haita11dcb62017-12-04 13:36:50 +0530881 frappe.msgprint(__("Please select {0}", [opts.source_doctype]))
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530882 return;
883 }
884 opts.source_name = values;
Saqibe03d9aa2021-09-17 13:03:27 +0530885 if (opts.allow_child_item_selection) {
886 // args contains filtered child docnames
887 opts.args = args;
888 }
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530889 d.dialog.hide();
890 _map();
891 },
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530892 });
Sagar Vora78777d62021-03-09 20:35:08 +0530893
894 return d;
895 }
896
897 if (opts.source_name) {
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530898 opts.source_name = [opts.source_name];
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530899 _map();
900 }
901}
902
Rushabh Mehta180e4352016-07-26 17:57:42 +0530903frappe.form.link_formatters['Item'] = function(value, doc) {
Alan157b3882021-04-21 21:00:22 +0530904 if (doc && value && doc.item_name && doc.item_name !== value && doc.item_code === value) {
marination824f48f2020-10-12 20:08:03 +0530905 return value + ': ' + doc.item_name;
906 } else if (!value && doc.doctype && doc.item_name) {
907 // format blank value in child table
908 return doc.item_name;
Rushabh Mehta180e4352016-07-26 17:57:42 +0530909 } else {
marination824f48f2020-10-12 20:08:03 +0530910 // 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 +0530911 return value;
912 }
913}
914
915frappe.form.link_formatters['Employee'] = function(value, doc) {
Rucha Mahabal5ba1bc12021-11-23 09:30:30 +0530916 if (doc && value && doc.employee_name && doc.employee_name !== value && doc.employee === value) {
917 return value + ': ' + doc.employee_name;
918 } else if (!value && doc.doctype && doc.employee_name) {
919 // format blank value in child table
920 return doc.employee;
Rushabh Mehta180e4352016-07-26 17:57:42 +0530921 } else {
Rucha Mahabal5ba1bc12021-11-23 09:30:30 +0530922 // 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 +0530923 return value;
924 }
925}
926
Rucha Mahabal59961f72021-05-20 23:43:19 +0530927frappe.form.link_formatters['Project'] = function(value, doc) {
928 if (doc && value && doc.project_name && doc.project_name !== value && doc.project === value) {
929 return value + ': ' + doc.project_name;
930 } else if (!value && doc.doctype && doc.project_name) {
931 // format blank value in child table
932 return doc.project;
933 } else {
934 // if value is blank in report view or project name and name are the same, return as is
935 return value;
936 }
937};
938
Rushabh Mehta95b995b2015-05-28 12:10:55 +0530939// add description on posting time
940$(document).on('app_ready', function() {
941 if(!frappe.datetime.is_timezone_same()) {
942 $.each(["Stock Reconciliation", "Stock Entry", "Stock Ledger Entry",
943 "Delivery Note", "Purchase Receipt", "Sales Invoice"], function(i, d) {
944 frappe.ui.form.on(d, "onload", function(frm) {
945 cur_frm.set_df_property("posting_time", "description",
Faris Ansariab74ca72017-05-30 12:54:42 +0530946 frappe.sys_defaults.time_zone);
Rushabh Mehta95b995b2015-05-28 12:10:55 +0530947 });
948 });
949 }
akshay14384c22016-07-28 13:53:17 +0530950});
Alanc6dc9ea2021-05-07 20:30:04 +0530951
Himanshuec25d592021-06-14 19:05:52 +0530952// Show SLA dashboard
953$(document).on('app_ready', function() {
Ankush Menatbd9ef742023-07-16 11:34:42 +0530954 $.each(frappe.boot.service_level_agreement_doctypes, function(_i, d) {
955 frappe.ui.form.on(d, {
956 onload: function(frm) {
957 if (!frm.doc.service_level_agreement)
958 return;
Himanshuec25d592021-06-14 19:05:52 +0530959
Ankush Menatbd9ef742023-07-16 11:34:42 +0530960 frappe.call({
961 method: 'erpnext.support.doctype.service_level_agreement.service_level_agreement.get_service_level_agreement_filters',
962 args: {
963 doctype: frm.doc.doctype,
964 name: frm.doc.service_level_agreement,
965 customer: frm.doc.customer
Himanshuec25d592021-06-14 19:05:52 +0530966 },
Ankush Menatbd9ef742023-07-16 11:34:42 +0530967 callback: function (r) {
968 if (r && r.message) {
969 frm.set_query('priority', function() {
970 return {
971 filters: {
972 'name': ['in', r.message.priority],
Himanshuec25d592021-06-14 19:05:52 +0530973 }
Ankush Menatbd9ef742023-07-16 11:34:42 +0530974 };
Himanshuec25d592021-06-14 19:05:52 +0530975 });
Ankush Menatbd9ef742023-07-16 11:34:42 +0530976 frm.set_query('service_level_agreement', function() {
977 return {
978 filters: {
979 'name': ['in', r.message.service_level_agreements],
980 }
981 };
982 });
Himanshuec25d592021-06-14 19:05:52 +0530983 }
Ankush Menatbd9ef742023-07-16 11:34:42 +0530984 }
Himanshuec25d592021-06-14 19:05:52 +0530985 });
Ankush Menatbd9ef742023-07-16 11:34:42 +0530986 },
987
988 refresh: function(frm) {
989 if (frm.doc.status !== 'Closed' && frm.doc.service_level_agreement
990 && ['First Response Due', 'Resolution Due'].includes(frm.doc.agreement_status)) {
991 frappe.call({
992 'method': 'frappe.client.get',
993 args: {
994 doctype: 'Service Level Agreement',
995 name: frm.doc.service_level_agreement
996 },
997 callback: function(data) {
998 let statuses = data.message.pause_sla_on;
999 const hold_statuses = [];
1000 $.each(statuses, (_i, entry) => {
1001 hold_statuses.push(entry.status);
1002 });
1003 if (hold_statuses.includes(frm.doc.status)) {
1004 frm.dashboard.clear_headline();
1005 let message = {'indicator': 'orange', 'msg': __('SLA is on hold since {0}', [moment(frm.doc.on_hold_since).fromNow(true)])};
1006 frm.dashboard.set_headline_alert(
1007 '<div class="row">' +
1008 '<div class="col-xs-12">' +
1009 '<span class="indicator whitespace-nowrap '+ message.indicator +'"><span>'+ message.msg +'</span></span> ' +
1010 '</div>' +
1011 '</div>'
1012 );
1013 } else {
1014 set_time_to_resolve_and_response(frm, data.message.apply_sla_for_resolution);
1015 }
1016 }
1017 });
1018 } else if (frm.doc.service_level_agreement) {
1019 frm.dashboard.clear_headline();
1020
1021 let agreement_status = (frm.doc.agreement_status == 'Fulfilled') ?
1022 {'indicator': 'green', 'msg': 'Service Level Agreement has been fulfilled'} :
1023 {'indicator': 'red', 'msg': 'Service Level Agreement Failed'};
1024
1025 frm.dashboard.set_headline_alert(
1026 '<div class="row">' +
1027 '<div class="col-xs-12">' +
1028 '<span class="indicator whitespace-nowrap '+ agreement_status.indicator +'"><span class="hidden-xs">'+ agreement_status.msg +'</span></span> ' +
1029 '</div>' +
1030 '</div>'
1031 );
1032 }
1033 },
1034 });
Himanshuec25d592021-06-14 19:05:52 +05301035 });
1036});
1037
1038function set_time_to_resolve_and_response(frm, apply_sla_for_resolution) {
1039 frm.dashboard.clear_headline();
1040
Saqib24114772021-12-15 11:45:34 +05301041 let time_to_respond;
Saqib Ansari476e81a2021-12-06 18:55:30 +05301042 if (!frm.doc.first_responded_on) {
Himanshuec25d592021-06-14 19:05:52 +05301043 time_to_respond = get_time_left(frm.doc.response_by, frm.doc.agreement_status);
Saqib24114772021-12-15 11:45:34 +05301044 } else {
1045 time_to_respond = get_status(frm.doc.response_by, frm.doc.first_responded_on);
Himanshuec25d592021-06-14 19:05:52 +05301046 }
1047
1048 let alert = `
1049 <div class="row">
1050 <div class="col-xs-12 col-sm-6">
1051 <span class="indicator whitespace-nowrap ${time_to_respond.indicator}">
1052 <span>Time to Respond: ${time_to_respond.diff_display}</span>
1053 </span>
1054 </div>`;
1055
1056
1057 if (apply_sla_for_resolution) {
Saqib24114772021-12-15 11:45:34 +05301058 let time_to_resolve;
Saqib Ansari476e81a2021-12-06 18:55:30 +05301059 if (!frm.doc.resolution_date) {
Himanshuec25d592021-06-14 19:05:52 +05301060 time_to_resolve = get_time_left(frm.doc.resolution_by, frm.doc.agreement_status);
Saqib24114772021-12-15 11:45:34 +05301061 } else {
1062 time_to_resolve = get_status(frm.doc.resolution_by, frm.doc.resolution_date);
Himanshuec25d592021-06-14 19:05:52 +05301063 }
1064
1065 alert += `
1066 <div class="col-xs-12 col-sm-6">
1067 <span class="indicator whitespace-nowrap ${time_to_resolve.indicator}">
1068 <span>Time to Resolve: ${time_to_resolve.diff_display}</span>
1069 </span>
1070 </div>`;
1071 }
1072
1073 alert += '</div>';
1074
1075 frm.dashboard.set_headline_alert(alert);
1076}
1077
1078function get_time_left(timestamp, agreement_status) {
1079 const diff = moment(timestamp).diff(moment());
1080 const diff_display = diff >= 44500 ? moment.duration(diff).humanize() : 'Failed';
1081 let indicator = (diff_display == 'Failed' && agreement_status != 'Fulfilled') ? 'red' : 'green';
1082 return {'diff_display': diff_display, 'indicator': indicator};
1083}
1084
Saqib24114772021-12-15 11:45:34 +05301085function get_status(expected, actual) {
1086 const time_left = moment(expected).diff(moment(actual));
Saqib Ansari476e81a2021-12-06 18:55:30 +05301087 if (time_left >= 0) {
Himanshuec25d592021-06-14 19:05:52 +05301088 return {'diff_display': 'Fulfilled', 'indicator': 'green'};
1089 } else {
1090 return {'diff_display': 'Failed', 'indicator': 'red'};
1091 }
1092}
1093
Alanc6dc9ea2021-05-07 20:30:04 +05301094function attach_selector_button(inner_text, append_loction, context, grid_row) {
1095 let $btn_div = $("<div>").css({"margin-bottom": "10px", "margin-top": "10px"})
1096 .appendTo(append_loction);
1097 let $btn = $(`<button class="btn btn-sm btn-default">${inner_text}</button>`)
1098 .appendTo($btn_div);
1099
1100 $btn.on("click", function() {
1101 context.show_serial_batch_selector(grid_row.frm, grid_row.doc, "", "", true);
1102 });
ruthra kumar5981c7e2023-08-29 13:19:26 +05301103}