blob: b0ea56833b7fbcbee2ca87c13c95392ca74468b1 [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() {
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
ruthra kumarc31ee8e2023-11-14 06:44:49 +0530407 get_fiscal_year: function(date, with_dates=false, boolean=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: {
ruthra kumarc31ee8e2023-11-14 06:44:49 +0530416 date: date,
417 boolean: boolean
Deepesh Garg62706072023-07-16 12:58:42 +0530418 },
419 async: false,
420 callback: function(r) {
421 if (r.message) {
Deepesh Garg4496a672023-07-24 11:58:16 +0530422 if (with_dates)
423 fiscal_year = r.message;
424 else
425 fiscal_year = r.message[0];
Deepesh Garg62706072023-07-16 12:58:42 +0530426 }
427 }
428 });
429 return fiscal_year;
Rohit Waghchaure1c2fe082023-06-15 12:54:43 +0530430 }
Rushabh Mehta95b995b2015-05-28 12:10:55 +0530431});
432
rohitwaghchaurea3c3dec2018-03-28 11:51:44 +0530433erpnext.utils.select_alternate_items = function(opts) {
434 const frm = opts.frm;
435 const warehouse_field = opts.warehouse_field || 'warehouse';
436 const item_field = opts.item_field || 'item_code';
437
438 this.data = [];
439 const dialog = new frappe.ui.Dialog({
440 title: __("Select Alternate Item"),
441 fields: [
442 {fieldtype:'Section Break', label: __('Items')},
443 {
444 fieldname: "alternative_items", fieldtype: "Table", cannot_add_rows: true,
445 in_place_edit: true, data: this.data,
446 get_data: () => {
447 return this.data;
448 },
449 fields: [{
450 fieldtype:'Data',
451 fieldname:"docname",
452 hidden: 1
453 }, {
454 fieldtype:'Link',
455 fieldname:"item_code",
456 options: 'Item',
457 in_list_view: 1,
458 read_only: 1,
459 label: __('Item Code')
460 }, {
461 fieldtype:'Link',
462 fieldname:"alternate_item",
463 options: 'Item',
464 default: "",
465 in_list_view: 1,
466 label: __('Alternate Item'),
467 onchange: function() {
468 const item_code = this.get_value();
469 const warehouse = this.grid_row.on_grid_fields_dict.warehouse.get_value();
470 if (item_code && warehouse) {
471 frappe.call({
472 method: "erpnext.stock.utils.get_latest_stock_qty",
473 args: {
474 item_code: item_code,
475 warehouse: warehouse
476 },
477 callback: (r) => {
478 this.grid_row.on_grid_fields_dict
479 .actual_qty.set_value(r.message || 0);
480 }
481 })
482 }
483 },
484 get_query: (e) => {
485 return {
486 query: "erpnext.stock.doctype.item_alternative.item_alternative.get_alternative_items",
487 filters: {
488 item_code: e.item_code
489 }
490 };
491 }
492 }, {
493 fieldtype:'Link',
494 fieldname:"warehouse",
495 options: 'Warehouse',
496 default: "",
497 in_list_view: 1,
498 label: __('Warehouse'),
499 onchange: function() {
500 const warehouse = this.get_value();
501 const item_code = this.grid_row.on_grid_fields_dict.item_code.get_value();
502 if (item_code && warehouse) {
503 frappe.call({
504 method: "erpnext.stock.utils.get_latest_stock_qty",
505 args: {
506 item_code: item_code,
507 warehouse: warehouse
508 },
509 callback: (r) => {
510 this.grid_row.on_grid_fields_dict
511 .actual_qty.set_value(r.message || 0);
512 }
513 })
514 }
515 },
516 }, {
517 fieldtype:'Float',
518 fieldname:"actual_qty",
519 default: 0,
520 read_only: 1,
521 in_list_view: 1,
522 label: __('Available Qty')
523 }]
524 },
525 ],
526 primary_action: function() {
527 const args = this.get_values()["alternative_items"];
528 const alternative_items = args.filter(d => {
529 if (d.alternate_item && d.item_code != d.alternate_item) {
530 return true;
531 }
532 });
533
534 alternative_items.forEach(d => {
535 let row = frappe.get_doc(opts.child_doctype, d.docname);
Doridel Cahanape42192b2018-05-16 13:28:39 +0800536 let qty = null;
537 if (row.doctype === 'Work Order Item') {
538 qty = row.required_qty;
539 } else {
540 qty = row.qty;
541 }
rohitwaghchaurea3c3dec2018-03-28 11:51:44 +0530542 row[item_field] = d.alternate_item;
mergify[bot]c1a0f642021-12-17 19:06:19 +0530543 frappe.model.set_value(row.doctype, row.name, 'qty', qty);
544 frappe.model.set_value(row.doctype, row.name, opts.original_item_field, d.item_code);
545 frm.trigger(item_field, row.doctype, row.name);
rohitwaghchaurea3c3dec2018-03-28 11:51:44 +0530546 });
547
548 refresh_field(opts.child_docname);
549 this.hide();
550 },
551 primary_action_label: __('Update')
552 });
553
554 frm.doc[opts.child_docname].forEach(d => {
555 if (!opts.condition || opts.condition(d)) {
556 dialog.fields_dict.alternative_items.df.data.push({
557 "docname": d.name,
558 "item_code": d[item_field],
559 "warehouse": d[warehouse_field],
560 "actual_qty": d.actual_qty
561 });
562 }
563 })
564
565 this.data = dialog.fields_dict.alternative_items.df.data;
566 dialog.fields_dict.alternative_items.grid.refresh();
567 dialog.show();
568}
569
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800570erpnext.utils.update_child_items = function(opts) {
571 const frm = opts.frm;
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +0100572 const cannot_add_row = (typeof opts.cannot_add_row === 'undefined') ? true : opts.cannot_add_row;
573 const child_docname = (typeof opts.cannot_add_row === 'undefined') ? "items" : opts.child_docname;
Saqib56fea7d2020-10-09 21:19:25 +0530574 const child_meta = frappe.get_meta(`${frm.doc.doctype} Item`);
s-aga-r2d8363a2023-09-02 11:02:24 +0530575 const has_reserved_stock = opts.has_reserved_stock ? true : false;
Saqib56fea7d2020-10-09 21:19:25 +0530576 const get_precision = (fieldname) => child_meta.fields.find(f => f.fieldname == fieldname).precision;
577
Devin Slauenwhitea835c1a2023-01-26 16:53:05 -0500578 this.data = frm.doc[opts.child_docname].map((d) => {
579 return {
580 "docname": d.name,
581 "name": d.name,
582 "item_code": d.item_code,
583 "delivery_date": d.delivery_date,
584 "schedule_date": d.schedule_date,
585 "conversion_factor": d.conversion_factor,
586 "qty": d.qty,
587 "rate": d.rate,
s-aga-r9588bb72023-08-21 22:23:57 +0530588 "uom": d.uom,
589 "fg_item": d.fg_item,
590 "fg_item_qty": d.fg_item_qty,
Devin Slauenwhitea835c1a2023-01-26 16:53:05 -0500591 }
592 });
593
Saqib Ansarif53299e2020-04-15 22:08:12 +0530594 const fields = [{
595 fieldtype:'Data',
596 fieldname:"docname",
597 read_only: 1,
598 hidden: 1,
599 }, {
600 fieldtype:'Link',
601 fieldname:"item_code",
602 options: 'Item',
603 in_list_view: 1,
604 read_only: 0,
605 disabled: 0,
Afshandc7280e2021-08-18 17:44:40 +0530606 label: __('Item Code'),
607 get_query: function() {
608 let filters;
609 if (frm.doc.doctype == 'Sales Order') {
610 filters = {"is_sales_item": 1};
611 } else if (frm.doc.doctype == 'Purchase Order') {
Sagar Sharmad074c932022-03-31 19:57:42 +0530612 if (frm.doc.is_subcontracted) {
s-aga-r6d89b2f2022-06-18 15:46:59 +0530613 if (frm.doc.is_old_subcontracting_flow) {
614 filters = {"is_sub_contracted_item": 1};
615 } else {
616 filters = {"is_stock_item": 0};
617 }
Afshandc7280e2021-08-18 17:44:40 +0530618 } else {
619 filters = {"is_purchase_item": 1};
620 }
621 }
622 return {
623 query: "erpnext.controllers.queries.item_query",
624 filters: filters
625 };
626 }
Saqib Ansarif53299e2020-04-15 22:08:12 +0530627 }, {
Saqib61314242020-09-15 11:14:31 +0530628 fieldtype:'Link',
629 fieldname:'uom',
630 options: 'UOM',
631 read_only: 0,
632 label: __('UOM'),
633 reqd: 1,
634 onchange: function () {
635 frappe.call({
636 method: "erpnext.stock.get_item_details.get_conversion_factor",
637 args: { item_code: this.doc.item_code, uom: this.value },
638 callback: r => {
639 if(!r.exc) {
640 if (this.doc.conversion_factor == r.message.conversion_factor) return;
marination4f395cc2020-09-24 12:43:41 +0530641
Saqib61314242020-09-15 11:14:31 +0530642 const docname = this.doc.docname;
643 dialog.fields_dict.trans_items.df.data.some(doc => {
644 if (doc.docname == docname) {
645 doc.conversion_factor = r.message.conversion_factor;
646 dialog.fields_dict.trans_items.grid.refresh();
647 return true;
648 }
649 })
650 }
651 }
652 });
653 }
654 }, {
Saqib Ansarif53299e2020-04-15 22:08:12 +0530655 fieldtype:'Float',
656 fieldname:"qty",
657 default: 0,
658 read_only: 0,
659 in_list_view: 1,
Saqib56fea7d2020-10-09 21:19:25 +0530660 label: __('Qty'),
661 precision: get_precision("qty")
Saqib Ansarif53299e2020-04-15 22:08:12 +0530662 }, {
663 fieldtype:'Currency',
664 fieldname:"rate",
Afshan84184552021-02-24 16:51:11 +0530665 options: "currency",
Saqib Ansarif53299e2020-04-15 22:08:12 +0530666 default: 0,
667 read_only: 0,
668 in_list_view: 1,
Saqib56fea7d2020-10-09 21:19:25 +0530669 label: __('Rate'),
670 precision: get_precision("rate")
Saqib Ansarif53299e2020-04-15 22:08:12 +0530671 }];
672
673 if (frm.doc.doctype == 'Sales Order' || frm.doc.doctype == 'Purchase Order' ) {
674 fields.splice(2, 0, {
675 fieldtype: 'Date',
676 fieldname: frm.doc.doctype == 'Sales Order' ? "delivery_date" : "schedule_date",
677 in_list_view: 1,
Saqib Ansaric579b082020-05-29 22:21:50 +0530678 label: frm.doc.doctype == 'Sales Order' ? __("Delivery Date") : __("Reqd by date"),
679 reqd: 1
Saqib Ansarif53299e2020-04-15 22:08:12 +0530680 })
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +0530681 fields.splice(3, 0, {
682 fieldtype: 'Float',
683 fieldname: "conversion_factor",
Saqib56fea7d2020-10-09 21:19:25 +0530684 label: __("Conversion Factor"),
685 precision: get_precision('conversion_factor')
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +0530686 })
Saqib Ansarif53299e2020-04-15 22:08:12 +0530687 }
688
s-aga-rfaf9f132023-08-21 15:51:57 +0530689 if (frm.doc.doctype == 'Purchase Order' && frm.doc.is_subcontracted && !frm.doc.is_old_subcontracting_flow) {
690 fields.push({
691 fieldtype:'Link',
692 fieldname:'fg_item',
693 options: 'Item',
694 reqd: 1,
695 in_list_view: 0,
696 read_only: 0,
697 disabled: 0,
698 label: __('Finished Good Item'),
699 get_query: () => {
700 return {
701 filters: {
702 'is_stock_item': 1,
703 'is_sub_contracted_item': 1,
704 'default_bom': ['!=', '']
705 }
706 }
707 },
708 }, {
709 fieldtype:'Float',
710 fieldname:'fg_item_qty',
711 reqd: 1,
712 default: 0,
713 read_only: 0,
714 in_list_view: 0,
715 label: __('Finished Good Item Qty'),
716 precision: get_precision('fg_item_qty')
717 })
718 }
719
Deepesh Garg40772542023-07-22 23:07:18 +0530720 let dialog = new frappe.ui.Dialog({
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800721 title: __("Update Items"),
Raffael Meyerd5fe1432023-07-14 08:57:35 +0200722 size: "extra-large",
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800723 fields: [
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800724 {
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +0100725 fieldname: "trans_items",
726 fieldtype: "Table",
Maricafc96c1a2020-03-06 10:57:59 +0530727 label: "Items",
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +0100728 cannot_add_rows: cannot_add_row,
Saqibbc919e22020-11-05 17:38:35 +0530729 in_place_edit: false,
Maricafc96c1a2020-03-06 10:57:59 +0530730 reqd: 1,
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +0100731 data: this.data,
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800732 get_data: () => {
733 return this.data;
734 },
Saqib Ansarif53299e2020-04-15 22:08:12 +0530735 fields: fields
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800736 },
737 ],
738 primary_action: function() {
s-aga-r2d8363a2023-09-02 11:02:24 +0530739 if (frm.doctype == "Sales Order" && has_reserved_stock) {
740 this.hide();
741 frappe.confirm(
742 __('The reserved stock will be released when you update items. Are you certain you wish to proceed?'),
743 () => this.update_items(),
744 )
745 } else {
746 this.update_items();
747 }
748 },
749 update_items: function() {
Ankush Menat6de7b8e2021-08-24 12:18:40 +0530750 const trans_items = this.get_values()["trans_items"].filter((item) => !!item.item_code);
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800751 frappe.call({
752 method: 'erpnext.controllers.accounts_controller.update_child_qty_rate',
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +0100753 freeze: true,
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800754 args: {
755 'parent_doctype': frm.doc.doctype,
756 'trans_items': trans_items,
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +0100757 'parent_doctype_name': frm.doc.name,
758 'child_docname': child_docname
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800759 },
760 callback: function() {
761 frm.reload_doc();
762 }
763 });
764 this.hide();
765 refresh_field("items");
766 },
767 primary_action_label: __('Update')
Deepesh Garg40772542023-07-22 23:07:18 +0530768 })
769
770 dialog.show();
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800771}
772
ruthra kumar5981c7e2023-08-29 13:19:26 +0530773
ruthra kumar5981c7e2023-08-29 13:19:26 +0530774
ruthra kumar5981c7e2023-08-29 13:19:26 +0530775
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530776erpnext.utils.map_current_doc = function(opts) {
Sagar Vora78777d62021-03-09 20:35:08 +0530777 function _map() {
Rushabh Mehta55ea7b12016-07-15 16:43:25 +0530778 if($.isArray(cur_frm.doc.items) && cur_frm.doc.items.length > 0) {
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530779 // remove first item row if empty
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530780 if(!cur_frm.doc.items[0].item_code) {
781 cur_frm.doc.items = cur_frm.doc.items.splice(1);
782 }
bhupen3c7e70f2016-11-30 14:32:11 +0530783
784 // find the doctype of the items table
785 var items_doctype = frappe.meta.get_docfield(cur_frm.doctype, 'items').options;
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530786
bhupen3c7e70f2016-11-30 14:32:11 +0530787 // find the link fieldname from items table for the given
788 // source_doctype
789 var link_fieldname = null;
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530790 frappe.get_meta(items_doctype).fields.forEach(function(d) {
bhupen3c7e70f2016-11-30 14:32:11 +0530791 if(d.options===opts.source_doctype) link_fieldname = d.fieldname; });
792
Nabin Hait802b4352017-01-09 15:32:20 +0530793 // search in existing items if the source_name is already set and full qty fetched
bhupen3c7e70f2016-11-30 14:32:11 +0530794 var already_set = false;
Nabin Hait802b4352017-01-09 15:32:20 +0530795 var item_qty_map = {};
bhupen3c7e70f2016-11-30 14:32:11 +0530796
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530797 $.each(cur_frm.doc.items, function(i, d) {
798 opts.source_name.forEach(function(src) {
799 if(d[link_fieldname]==src) {
800 already_set = true;
801 if (item_qty_map[d.item_code])
802 item_qty_map[d.item_code] += flt(d.qty);
803 else
804 item_qty_map[d.item_code] = flt(d.qty);
805 }
806 });
807 });
808
809 if(already_set) {
810 opts.source_name.forEach(function(src) {
811 frappe.model.with_doc(opts.source_doctype, src, function(r) {
812 var source_doc = frappe.model.get_doc(opts.source_doctype, src);
813 $.each(source_doc.items || [], function(i, row) {
814 if(row.qty > flt(item_qty_map[row.item_code])) {
815 already_set = false;
816 return false;
817 }
818 })
819 })
820
821 if(already_set) {
822 frappe.msgprint(__("You have already selected items from {0} {1}",
823 [opts.source_doctype, src]));
824 return;
825 }
826
827 })
Nabin Hait802b4352017-01-09 15:32:20 +0530828 }
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530829 }
830
831 return frappe.call({
832 // Sometimes we hit the limit for URL length of a GET request
833 // as we send the full target_doc. Hence this is a POST request.
834 type: "POST",
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530835 method: 'frappe.model.mapper.map_docs',
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530836 args: {
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530837 "method": opts.method,
838 "source_names": opts.source_name,
839 "target_doc": cur_frm.doc,
Maricadb002702020-02-17 15:58:08 +0530840 "args": opts.args
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530841 },
s-aga-r2d8363a2023-09-02 11:02:24 +0530842 freeze: true,
843 freeze_message: __("Mapping {0} ...", [opts.source_doctype]),
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530844 callback: function(r) {
845 if(!r.exc) {
846 var doc = frappe.model.sync(r.message);
Vishal Dhayagudef06c2812017-12-26 16:22:40 +0530847 cur_frm.dirty();
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530848 cur_frm.refresh();
849 }
850 }
851 });
852 }
Sagar Vora78777d62021-03-09 20:35:08 +0530853
854 let query_args = {};
855 if (opts.get_query_filters) {
856 query_args.filters = opts.get_query_filters;
857 }
858
859 if (opts.get_query_method) {
860 query_args.query = opts.get_query_method;
861 }
862
863 if (query_args.filters || query_args.query) {
864 opts.get_query = () => query_args;
865 }
866
867 if (opts.source_doctype) {
868 const d = new frappe.ui.form.MultiSelectDialog({
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530869 doctype: opts.source_doctype,
870 target: opts.target,
871 date_field: opts.date_field || undefined,
872 setters: opts.setters,
873 get_query: opts.get_query,
marination4f395cc2020-09-24 12:43:41 +0530874 add_filters_group: 1,
Saqib7292f542021-09-13 12:13:43 +0530875 allow_child_item_selection: opts.allow_child_item_selection,
gn3060292a619fd2022-06-29 17:15:21 +0800876 child_fieldname: opts.child_fieldname,
Saqib7292f542021-09-13 12:13:43 +0530877 child_columns: opts.child_columns,
Rohit Waghchaure69ffddf2021-10-07 17:33:58 +0530878 size: opts.size,
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530879 action: function(selections, args) {
880 let values = selections;
Saqibe03d9aa2021-09-17 13:03:27 +0530881 if (values.length === 0) {
Nabin Haita11dcb62017-12-04 13:36:50 +0530882 frappe.msgprint(__("Please select {0}", [opts.source_doctype]))
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530883 return;
884 }
885 opts.source_name = values;
Saqibe03d9aa2021-09-17 13:03:27 +0530886 if (opts.allow_child_item_selection) {
887 // args contains filtered child docnames
888 opts.args = args;
889 }
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530890 d.dialog.hide();
891 _map();
892 },
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530893 });
Sagar Vora78777d62021-03-09 20:35:08 +0530894
895 return d;
896 }
897
898 if (opts.source_name) {
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530899 opts.source_name = [opts.source_name];
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530900 _map();
901 }
902}
903
Rushabh Mehta180e4352016-07-26 17:57:42 +0530904frappe.form.link_formatters['Item'] = function(value, doc) {
Alan157b3882021-04-21 21:00:22 +0530905 if (doc && value && doc.item_name && doc.item_name !== value && doc.item_code === value) {
marination824f48f2020-10-12 20:08:03 +0530906 return value + ': ' + doc.item_name;
907 } else if (!value && doc.doctype && doc.item_name) {
908 // format blank value in child table
909 return doc.item_name;
Rushabh Mehta180e4352016-07-26 17:57:42 +0530910 } else {
marination824f48f2020-10-12 20:08:03 +0530911 // 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 +0530912 return value;
913 }
914}
915
916frappe.form.link_formatters['Employee'] = function(value, doc) {
Rucha Mahabal5ba1bc12021-11-23 09:30:30 +0530917 if (doc && value && doc.employee_name && doc.employee_name !== value && doc.employee === value) {
918 return value + ': ' + doc.employee_name;
919 } else if (!value && doc.doctype && doc.employee_name) {
920 // format blank value in child table
921 return doc.employee;
Rushabh Mehta180e4352016-07-26 17:57:42 +0530922 } else {
Rucha Mahabal5ba1bc12021-11-23 09:30:30 +0530923 // 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 +0530924 return value;
925 }
926}
927
Rucha Mahabal59961f72021-05-20 23:43:19 +0530928frappe.form.link_formatters['Project'] = function(value, doc) {
929 if (doc && value && doc.project_name && doc.project_name !== value && doc.project === value) {
930 return value + ': ' + doc.project_name;
931 } else if (!value && doc.doctype && doc.project_name) {
932 // format blank value in child table
933 return doc.project;
934 } else {
935 // if value is blank in report view or project name and name are the same, return as is
936 return value;
937 }
938};
939
Rushabh Mehta95b995b2015-05-28 12:10:55 +0530940// add description on posting time
941$(document).on('app_ready', function() {
942 if(!frappe.datetime.is_timezone_same()) {
943 $.each(["Stock Reconciliation", "Stock Entry", "Stock Ledger Entry",
944 "Delivery Note", "Purchase Receipt", "Sales Invoice"], function(i, d) {
945 frappe.ui.form.on(d, "onload", function(frm) {
946 cur_frm.set_df_property("posting_time", "description",
Faris Ansariab74ca72017-05-30 12:54:42 +0530947 frappe.sys_defaults.time_zone);
Rushabh Mehta95b995b2015-05-28 12:10:55 +0530948 });
949 });
950 }
akshay14384c22016-07-28 13:53:17 +0530951});
Alanc6dc9ea2021-05-07 20:30:04 +0530952
Himanshuec25d592021-06-14 19:05:52 +0530953// Show SLA dashboard
954$(document).on('app_ready', function() {
Ankush Menatbd9ef742023-07-16 11:34:42 +0530955 $.each(frappe.boot.service_level_agreement_doctypes, function(_i, d) {
956 frappe.ui.form.on(d, {
957 onload: function(frm) {
958 if (!frm.doc.service_level_agreement)
959 return;
Himanshuec25d592021-06-14 19:05:52 +0530960
Ankush Menatbd9ef742023-07-16 11:34:42 +0530961 frappe.call({
962 method: 'erpnext.support.doctype.service_level_agreement.service_level_agreement.get_service_level_agreement_filters',
963 args: {
964 doctype: frm.doc.doctype,
965 name: frm.doc.service_level_agreement,
966 customer: frm.doc.customer
Himanshuec25d592021-06-14 19:05:52 +0530967 },
Ankush Menatbd9ef742023-07-16 11:34:42 +0530968 callback: function (r) {
969 if (r && r.message) {
970 frm.set_query('priority', function() {
971 return {
972 filters: {
973 'name': ['in', r.message.priority],
Himanshuec25d592021-06-14 19:05:52 +0530974 }
Ankush Menatbd9ef742023-07-16 11:34:42 +0530975 };
Himanshuec25d592021-06-14 19:05:52 +0530976 });
Ankush Menatbd9ef742023-07-16 11:34:42 +0530977 frm.set_query('service_level_agreement', function() {
978 return {
979 filters: {
980 'name': ['in', r.message.service_level_agreements],
981 }
982 };
983 });
Himanshuec25d592021-06-14 19:05:52 +0530984 }
Ankush Menatbd9ef742023-07-16 11:34:42 +0530985 }
Himanshuec25d592021-06-14 19:05:52 +0530986 });
Ankush Menatbd9ef742023-07-16 11:34:42 +0530987 },
988
989 refresh: function(frm) {
990 if (frm.doc.status !== 'Closed' && frm.doc.service_level_agreement
991 && ['First Response Due', 'Resolution Due'].includes(frm.doc.agreement_status)) {
992 frappe.call({
993 'method': 'frappe.client.get',
994 args: {
995 doctype: 'Service Level Agreement',
996 name: frm.doc.service_level_agreement
997 },
998 callback: function(data) {
999 let statuses = data.message.pause_sla_on;
1000 const hold_statuses = [];
1001 $.each(statuses, (_i, entry) => {
1002 hold_statuses.push(entry.status);
1003 });
1004 if (hold_statuses.includes(frm.doc.status)) {
1005 frm.dashboard.clear_headline();
1006 let message = {'indicator': 'orange', 'msg': __('SLA is on hold since {0}', [moment(frm.doc.on_hold_since).fromNow(true)])};
1007 frm.dashboard.set_headline_alert(
1008 '<div class="row">' +
1009 '<div class="col-xs-12">' +
1010 '<span class="indicator whitespace-nowrap '+ message.indicator +'"><span>'+ message.msg +'</span></span> ' +
1011 '</div>' +
1012 '</div>'
1013 );
1014 } else {
1015 set_time_to_resolve_and_response(frm, data.message.apply_sla_for_resolution);
1016 }
1017 }
1018 });
1019 } else if (frm.doc.service_level_agreement) {
1020 frm.dashboard.clear_headline();
1021
1022 let agreement_status = (frm.doc.agreement_status == 'Fulfilled') ?
1023 {'indicator': 'green', 'msg': 'Service Level Agreement has been fulfilled'} :
1024 {'indicator': 'red', 'msg': 'Service Level Agreement Failed'};
1025
1026 frm.dashboard.set_headline_alert(
1027 '<div class="row">' +
1028 '<div class="col-xs-12">' +
1029 '<span class="indicator whitespace-nowrap '+ agreement_status.indicator +'"><span class="hidden-xs">'+ agreement_status.msg +'</span></span> ' +
1030 '</div>' +
1031 '</div>'
1032 );
1033 }
1034 },
1035 });
Himanshuec25d592021-06-14 19:05:52 +05301036 });
1037});
1038
1039function set_time_to_resolve_and_response(frm, apply_sla_for_resolution) {
1040 frm.dashboard.clear_headline();
1041
Saqib24114772021-12-15 11:45:34 +05301042 let time_to_respond;
Saqib Ansari476e81a2021-12-06 18:55:30 +05301043 if (!frm.doc.first_responded_on) {
Himanshuec25d592021-06-14 19:05:52 +05301044 time_to_respond = get_time_left(frm.doc.response_by, frm.doc.agreement_status);
Saqib24114772021-12-15 11:45:34 +05301045 } else {
1046 time_to_respond = get_status(frm.doc.response_by, frm.doc.first_responded_on);
Himanshuec25d592021-06-14 19:05:52 +05301047 }
1048
1049 let alert = `
1050 <div class="row">
1051 <div class="col-xs-12 col-sm-6">
1052 <span class="indicator whitespace-nowrap ${time_to_respond.indicator}">
1053 <span>Time to Respond: ${time_to_respond.diff_display}</span>
1054 </span>
1055 </div>`;
1056
1057
1058 if (apply_sla_for_resolution) {
Saqib24114772021-12-15 11:45:34 +05301059 let time_to_resolve;
Saqib Ansari476e81a2021-12-06 18:55:30 +05301060 if (!frm.doc.resolution_date) {
Himanshuec25d592021-06-14 19:05:52 +05301061 time_to_resolve = get_time_left(frm.doc.resolution_by, frm.doc.agreement_status);
Saqib24114772021-12-15 11:45:34 +05301062 } else {
1063 time_to_resolve = get_status(frm.doc.resolution_by, frm.doc.resolution_date);
Himanshuec25d592021-06-14 19:05:52 +05301064 }
1065
1066 alert += `
1067 <div class="col-xs-12 col-sm-6">
1068 <span class="indicator whitespace-nowrap ${time_to_resolve.indicator}">
1069 <span>Time to Resolve: ${time_to_resolve.diff_display}</span>
1070 </span>
1071 </div>`;
1072 }
1073
1074 alert += '</div>';
1075
1076 frm.dashboard.set_headline_alert(alert);
1077}
1078
1079function get_time_left(timestamp, agreement_status) {
Ankush Menateaf86a62023-12-14 15:53:57 +05301080 const diff = moment(timestamp).diff(frappe.datetime.system_datetime(true));
Himanshuec25d592021-06-14 19:05:52 +05301081 const diff_display = diff >= 44500 ? moment.duration(diff).humanize() : 'Failed';
1082 let indicator = (diff_display == 'Failed' && agreement_status != 'Fulfilled') ? 'red' : 'green';
1083 return {'diff_display': diff_display, 'indicator': indicator};
1084}
1085
Saqib24114772021-12-15 11:45:34 +05301086function get_status(expected, actual) {
1087 const time_left = moment(expected).diff(moment(actual));
Saqib Ansari476e81a2021-12-06 18:55:30 +05301088 if (time_left >= 0) {
Himanshuec25d592021-06-14 19:05:52 +05301089 return {'diff_display': 'Fulfilled', 'indicator': 'green'};
1090 } else {
1091 return {'diff_display': 'Failed', 'indicator': 'red'};
1092 }
1093}
1094
Alanc6dc9ea2021-05-07 20:30:04 +05301095function attach_selector_button(inner_text, append_loction, context, grid_row) {
1096 let $btn_div = $("<div>").css({"margin-bottom": "10px", "margin-top": "10px"})
1097 .appendTo(append_loction);
1098 let $btn = $(`<button class="btn btn-sm btn-default">${inner_text}</button>`)
1099 .appendTo($btn_div);
1100
1101 $btn.on("click", function() {
1102 context.show_serial_batch_selector(grid_row.frm, grid_row.doc, "", "", true);
1103 });
ruthra kumar5981c7e2023-08-29 13:19:26 +05301104}