blob: 58aa8d7da2332efe6c6970fce7292f38eefe3e50 [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
deepeshgarg00712f5cef2018-12-25 16:06:19 +0530116 add_indicator_for_multicompany: function(frm, info) {
Deepak867f2c62022-05-17 11:52:52 +0530117 frm.dashboard.stats_area.show();
deepeshgarg00712f5cef2018-12-25 16:06:19 +0530118 frm.dashboard.stats_area_row.addClass('flex');
119 frm.dashboard.stats_area_row.css('flex-wrap', 'wrap');
120
121 var color = info.total_unpaid ? 'orange' : 'green';
122
123 var indicator = $('<div class="flex-column col-xs-6">'+
124 '<div style="margin-top:10px"><h6>'+info.company+'</h6></div>'+
125
126 '<div class="badge-link small" style="margin-bottom:10px"><span class="indicator blue">'+
127 'Annual Billing: '+format_currency(info.billing_this_year, info.currency)+'</span></div>'+
128
129 '<div class="badge-link small" style="margin-bottom:10px">'+
130 '<span class="indicator '+color+'">Total Unpaid: '
131 +format_currency(info.total_unpaid, info.currency)+'</span></div>'+
132
133
134 '</div>').appendTo(frm.dashboard.stats_area_row);
135
136 if(info.loyalty_points){
137 $('<div class="badge-link small" style="margin-bottom:10px"><span class="indicator blue">'+
138 'Loyalty Points: '+info.loyalty_points+'</span></div>').appendTo(indicator);
139 }
140
141 return indicator;
142 },
143
Shreya Shah149f7ee2018-03-27 11:29:25 +0530144 get_party_name: function(party_type) {
145 var dict = {'Customer': 'customer_name', 'Supplier': 'supplier_name', 'Employee': 'employee_name',
146 'Member': 'member_name'};
147 return dict[party_type];
148 },
149
Rushabh Mehta49f97472018-08-30 18:50:48 +0530150 copy_value_in_all_rows: function(doc, dt, dn, table_fieldname, fieldname) {
Neil Trini Lasradofe2ffae2015-07-08 18:16:51 +0530151 var d = locals[dt][dn];
152 if(d[fieldname]){
153 var cl = doc[table_fieldname] || [];
154 for(var i = 0; i < cl.length; i++) {
155 if(!cl[i][fieldname]) cl[i][fieldname] = d[fieldname];
156 }
157 }
158 refresh_field(table_fieldname);
Makarand Bauskar157c3342017-05-26 21:32:33 +0530159 },
160
161 get_terms: function(tc_name, doc, callback) {
162 if(tc_name) {
163 return frappe.call({
164 method: 'erpnext.setup.doctype.terms_and_conditions.terms_and_conditions.get_terms_and_conditions',
165 args: {
166 template_name: tc_name,
167 doc: doc
168 },
169 callback: function(r) {
170 callback(r)
171 }
172 });
173 }
tundebabzy1a947db2017-08-29 13:48:27 +0100174 },
175
rohitwaghchaure713cfc72018-09-11 17:40:37 +0530176 make_bank_account: function(doctype, docname) {
177 frappe.call({
178 method: "erpnext.accounts.doctype.bank_account.bank_account.make_bank_account",
179 args: {
180 doctype: doctype,
181 docname: docname
182 },
183 freeze: true,
184 callback: function(r) {
185 var doclist = frappe.model.sync(r.message);
186 frappe.set_route("Form", doclist[0].doctype, doclist[0].name);
187 }
188 })
189 },
190
Deepesh Garg11ea0b12020-05-26 19:23:45 +0530191 add_dimensions: function(report_name, index) {
192 let filters = frappe.query_reports[report_name].filters;
193
Deepesh Garg7b2d5182020-12-04 11:28:26 +0530194 frappe.call({
195 method: "erpnext.accounts.doctype.accounting_dimension.accounting_dimension.get_dimensions",
196 callback: function(r) {
197 let accounting_dimensions = r.message[0];
198 accounting_dimensions.forEach((dimension) => {
199 let found = filters.some(el => el.fieldname === dimension['fieldname']);
Deepesh Garg11ea0b12020-05-26 19:23:45 +0530200
Deepesh Garg7b2d5182020-12-04 11:28:26 +0530201 if (!found) {
Deepesh Garg23ab5c52020-12-31 11:29:06 +0530202 filters.splice(index, 0, {
Deepesh Garg7b2d5182020-12-04 11:28:26 +0530203 "fieldname": dimension["fieldname"],
204 "label": __(dimension["label"]),
Rohit Waghchaure69be22b2022-05-14 17:19:34 +0530205 "fieldtype": "MultiSelectList",
206 get_data: function(txt) {
207 return frappe.db.get_link_options(dimension["document_type"], txt);
208 },
Deepesh Garg7b2d5182020-12-04 11:28:26 +0530209 });
210 }
Deepesh Garg11ea0b12020-05-26 19:23:45 +0530211 });
212 }
213 });
214 },
215
Rohit Waghchauredbec5cf2022-06-22 12:24:08 +0530216 add_inventory_dimensions: function(report_name, index) {
217 let filters = frappe.query_reports[report_name].filters;
218
219 frappe.call({
220 method: "erpnext.stock.doctype.inventory_dimension.inventory_dimension.get_inventory_dimensions",
221 callback: function(r) {
222 if (r.message && r.message.length) {
223 r.message.forEach((dimension) => {
Rohit Waghchaure0e388ba2023-02-20 12:20:03 +0530224 let existing_filter = filters.filter(el => el.fieldname === dimension['fieldname']);
Rohit Waghchauredbec5cf2022-06-22 12:24:08 +0530225
Rohit Waghchaure0e388ba2023-02-20 12:20:03 +0530226 if (!existing_filter.length) {
Rohit Waghchauredbec5cf2022-06-22 12:24:08 +0530227 filters.splice(index, 0, {
228 "fieldname": dimension["fieldname"],
Rohit Waghchaureef7def82022-09-07 14:40:18 +0530229 "label": __(dimension["doctype"]),
Rohit Waghchauredbec5cf2022-06-22 12:24:08 +0530230 "fieldtype": "MultiSelectList",
231 get_data: function(txt) {
232 return frappe.db.get_link_options(dimension["doctype"], txt);
233 },
234 });
Rohit Waghchaure0e388ba2023-02-20 12:20:03 +0530235 } else {
236 existing_filter[0]['fieldtype'] = "MultiSelectList";
237 existing_filter[0]['get_data'] = function(txt) {
238 return frappe.db.get_link_options(dimension["doctype"], txt);
239 }
Rohit Waghchauredbec5cf2022-06-22 12:24:08 +0530240 }
241 });
242 }
243 }
244 });
245 },
246
rohitwaghchaure166b78f2017-09-07 16:14:22 +0530247 make_subscription: function(doctype, docname) {
248 frappe.call({
Rucha Mahabal65a627c2019-07-17 13:50:32 +0530249 method: "frappe.automation.doctype.auto_repeat.auto_repeat.make_auto_repeat",
rohitwaghchaure166b78f2017-09-07 16:14:22 +0530250 args: {
251 doctype: doctype,
252 docname: docname
253 },
254 callback: function(r) {
255 var doclist = frappe.model.sync(r.message);
256 frappe.set_route("Form", doclist[0].doctype, doclist[0].name);
257 }
258 })
259 },
260
Saif90cf2dd2018-09-30 21:46:31 +0500261 make_pricing_rule: function(doctype, docname) {
262 frappe.call({
263 method: "erpnext.accounts.doctype.pricing_rule.pricing_rule.make_pricing_rule",
264 args: {
265 doctype: doctype,
266 docname: docname
267 },
268 callback: function(r) {
269 var doclist = frappe.model.sync(r.message);
270 frappe.set_route("Form", doclist[0].doctype, doclist[0].name);
271 }
272 })
273 },
274
tundebabzy1a947db2017-08-29 13:48:27 +0100275 /**
276 * Checks if the first row of a given child table is empty
277 * @param child_table - Child table Doctype
278 * @return {Boolean}
279 **/
280 first_row_is_empty: function(child_table){
281 if($.isArray(child_table) && child_table.length > 0) {
282 return !child_table[0].item_code;
283 }
284 return false;
285 },
286
287 /**
288 * Removes the first row of a child table if it is empty
289 * @param {_Frm} frm - The current form
290 * @param {String} child_table_name - The child table field name
291 * @return {Boolean}
292 **/
293 remove_empty_first_row: function(frm, child_table_name){
294 const rows = frm['doc'][child_table_name];
295 if (this.first_row_is_empty(rows)){
296 frm['doc'][child_table_name] = rows.splice(1);
297 }
298 return rows;
299 },
Zarrar6ffdf942018-06-14 12:24:16 +0530300 get_tree_options: function(option) {
301 // get valid options for tree based on user permission & locals dict
302 let unscrub_option = frappe.model.unscrub(option);
303 let user_permission = frappe.defaults.get_user_permissions();
deepeshgarg0070d64d622019-02-20 17:55:14 +0530304 let options;
305
Zarrar6ffdf942018-06-14 12:24:16 +0530306 if(user_permission && user_permission[unscrub_option]) {
deepeshgarg0070d64d622019-02-20 17:55:14 +0530307 options = user_permission[unscrub_option].map(perm => perm.doc);
Zarrar6ffdf942018-06-14 12:24:16 +0530308 } else {
deepeshgarg0070d64d622019-02-20 17:55:14 +0530309 options = $.map(locals[`:${unscrub_option}`], function(c) { return c.name; }).sort();
Zarrar6ffdf942018-06-14 12:24:16 +0530310 }
deepeshgarg0070d64d622019-02-20 17:55:14 +0530311
312 // filter unique values, as there may be multiple user permissions for any value
313 return options.filter((value, index, self) => self.indexOf(value) === index);
Zarrar6ffdf942018-06-14 12:24:16 +0530314 },
315 get_tree_default: function(option) {
316 // set default for a field based on user permission
317 let options = this.get_tree_options(option);
318 if(options.includes(frappe.defaults.get_default(option))) {
319 return frappe.defaults.get_default(option);
320 } else {
321 return options[0];
322 }
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400323 },
Andy Zhubffe9332021-04-12 22:49:26 +1200324 overrides_parent_value_in_all_rows: function(doc, dt, dn, table_fieldname, fieldname, parent_fieldname) {
Marica24e45162021-04-14 18:53:15 +0530325 if (doc[parent_fieldname]) {
Andy Zhubffe9332021-04-12 22:49:26 +1200326 let cl = doc[table_fieldname] || [];
Marica24e45162021-04-14 18:53:15 +0530327 for (let i = 0; i < cl.length; i++) {
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400328 cl[i][fieldname] = doc[parent_fieldname];
329 }
Andy Zhubffe9332021-04-12 22:49:26 +1200330 frappe.refresh_field(table_fieldname);
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400331 }
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400332 },
Nabin Hait34c551d2019-07-03 10:34:31 +0530333 create_new_doc: function (doctype, update_fields) {
334 frappe.model.with_doctype(doctype, function() {
335 var new_doc = frappe.model.get_new_doc(doctype);
336 for (let [key, value] of Object.entries(update_fields)) {
337 new_doc[key] = value;
338 }
339 frappe.ui.form.make_quick_entry(doctype, null, null, new_doc);
340 });
Ankush Menat0b86b1b2022-12-08 16:40:13 +0530341 },
Nabin Hait34c551d2019-07-03 10:34:31 +0530342
Ankush Menat0b86b1b2022-12-08 16:40:13 +0530343 // check if payments app is installed on site, if not warn user.
344 check_payments_app: () => {
345 if (frappe.boot.versions && !frappe.boot.versions.payments) {
346 const marketplace_link = '<a href="https://frappecloud.com/marketplace/apps/payments">Marketplace</a>'
347 const github_link = '<a href="https://github.com/frappe/payments/">GitHub</a>'
348 const msg = __("payments app is not installed. Please install it from {0} or {1}", [marketplace_link, github_link])
349 frappe.msgprint(msg);
350 }
351
352 },
Rushabh Mehta95b995b2015-05-28 12:10:55 +0530353});
354
rohitwaghchaurea3c3dec2018-03-28 11:51:44 +0530355erpnext.utils.select_alternate_items = function(opts) {
356 const frm = opts.frm;
357 const warehouse_field = opts.warehouse_field || 'warehouse';
358 const item_field = opts.item_field || 'item_code';
359
360 this.data = [];
361 const dialog = new frappe.ui.Dialog({
362 title: __("Select Alternate Item"),
363 fields: [
364 {fieldtype:'Section Break', label: __('Items')},
365 {
366 fieldname: "alternative_items", fieldtype: "Table", cannot_add_rows: true,
367 in_place_edit: true, data: this.data,
368 get_data: () => {
369 return this.data;
370 },
371 fields: [{
372 fieldtype:'Data',
373 fieldname:"docname",
374 hidden: 1
375 }, {
376 fieldtype:'Link',
377 fieldname:"item_code",
378 options: 'Item',
379 in_list_view: 1,
380 read_only: 1,
381 label: __('Item Code')
382 }, {
383 fieldtype:'Link',
384 fieldname:"alternate_item",
385 options: 'Item',
386 default: "",
387 in_list_view: 1,
388 label: __('Alternate Item'),
389 onchange: function() {
390 const item_code = this.get_value();
391 const warehouse = this.grid_row.on_grid_fields_dict.warehouse.get_value();
392 if (item_code && warehouse) {
393 frappe.call({
394 method: "erpnext.stock.utils.get_latest_stock_qty",
395 args: {
396 item_code: item_code,
397 warehouse: warehouse
398 },
399 callback: (r) => {
400 this.grid_row.on_grid_fields_dict
401 .actual_qty.set_value(r.message || 0);
402 }
403 })
404 }
405 },
406 get_query: (e) => {
407 return {
408 query: "erpnext.stock.doctype.item_alternative.item_alternative.get_alternative_items",
409 filters: {
410 item_code: e.item_code
411 }
412 };
413 }
414 }, {
415 fieldtype:'Link',
416 fieldname:"warehouse",
417 options: 'Warehouse',
418 default: "",
419 in_list_view: 1,
420 label: __('Warehouse'),
421 onchange: function() {
422 const warehouse = this.get_value();
423 const item_code = this.grid_row.on_grid_fields_dict.item_code.get_value();
424 if (item_code && warehouse) {
425 frappe.call({
426 method: "erpnext.stock.utils.get_latest_stock_qty",
427 args: {
428 item_code: item_code,
429 warehouse: warehouse
430 },
431 callback: (r) => {
432 this.grid_row.on_grid_fields_dict
433 .actual_qty.set_value(r.message || 0);
434 }
435 })
436 }
437 },
438 }, {
439 fieldtype:'Float',
440 fieldname:"actual_qty",
441 default: 0,
442 read_only: 1,
443 in_list_view: 1,
444 label: __('Available Qty')
445 }]
446 },
447 ],
448 primary_action: function() {
449 const args = this.get_values()["alternative_items"];
450 const alternative_items = args.filter(d => {
451 if (d.alternate_item && d.item_code != d.alternate_item) {
452 return true;
453 }
454 });
455
456 alternative_items.forEach(d => {
457 let row = frappe.get_doc(opts.child_doctype, d.docname);
Doridel Cahanape42192b2018-05-16 13:28:39 +0800458 let qty = null;
459 if (row.doctype === 'Work Order Item') {
460 qty = row.required_qty;
461 } else {
462 qty = row.qty;
463 }
rohitwaghchaurea3c3dec2018-03-28 11:51:44 +0530464 row[item_field] = d.alternate_item;
mergify[bot]c1a0f642021-12-17 19:06:19 +0530465 frappe.model.set_value(row.doctype, row.name, 'qty', qty);
466 frappe.model.set_value(row.doctype, row.name, opts.original_item_field, d.item_code);
467 frm.trigger(item_field, row.doctype, row.name);
rohitwaghchaurea3c3dec2018-03-28 11:51:44 +0530468 });
469
470 refresh_field(opts.child_docname);
471 this.hide();
472 },
473 primary_action_label: __('Update')
474 });
475
476 frm.doc[opts.child_docname].forEach(d => {
477 if (!opts.condition || opts.condition(d)) {
478 dialog.fields_dict.alternative_items.df.data.push({
479 "docname": d.name,
480 "item_code": d[item_field],
481 "warehouse": d[warehouse_field],
482 "actual_qty": d.actual_qty
483 });
484 }
485 })
486
487 this.data = dialog.fields_dict.alternative_items.df.data;
488 dialog.fields_dict.alternative_items.grid.refresh();
489 dialog.show();
490}
491
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800492erpnext.utils.update_child_items = function(opts) {
493 const frm = opts.frm;
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +0100494 const cannot_add_row = (typeof opts.cannot_add_row === 'undefined') ? true : opts.cannot_add_row;
495 const child_docname = (typeof opts.cannot_add_row === 'undefined') ? "items" : opts.child_docname;
Saqib56fea7d2020-10-09 21:19:25 +0530496 const child_meta = frappe.get_meta(`${frm.doc.doctype} Item`);
497 const get_precision = (fieldname) => child_meta.fields.find(f => f.fieldname == fieldname).precision;
498
Devin Slauenwhitea835c1a2023-01-26 16:53:05 -0500499 this.data = frm.doc[opts.child_docname].map((d) => {
500 return {
501 "docname": d.name,
502 "name": d.name,
503 "item_code": d.item_code,
504 "delivery_date": d.delivery_date,
505 "schedule_date": d.schedule_date,
506 "conversion_factor": d.conversion_factor,
507 "qty": d.qty,
508 "rate": d.rate,
509 "uom": d.uom
510 }
511 });
512
Saqib Ansarif53299e2020-04-15 22:08:12 +0530513 const fields = [{
514 fieldtype:'Data',
515 fieldname:"docname",
516 read_only: 1,
517 hidden: 1,
518 }, {
519 fieldtype:'Link',
520 fieldname:"item_code",
521 options: 'Item',
522 in_list_view: 1,
523 read_only: 0,
524 disabled: 0,
Afshandc7280e2021-08-18 17:44:40 +0530525 label: __('Item Code'),
526 get_query: function() {
527 let filters;
528 if (frm.doc.doctype == 'Sales Order') {
529 filters = {"is_sales_item": 1};
530 } else if (frm.doc.doctype == 'Purchase Order') {
Sagar Sharmad074c932022-03-31 19:57:42 +0530531 if (frm.doc.is_subcontracted) {
s-aga-r6d89b2f2022-06-18 15:46:59 +0530532 if (frm.doc.is_old_subcontracting_flow) {
533 filters = {"is_sub_contracted_item": 1};
534 } else {
535 filters = {"is_stock_item": 0};
536 }
Afshandc7280e2021-08-18 17:44:40 +0530537 } else {
538 filters = {"is_purchase_item": 1};
539 }
540 }
541 return {
542 query: "erpnext.controllers.queries.item_query",
543 filters: filters
544 };
545 }
Saqib Ansarif53299e2020-04-15 22:08:12 +0530546 }, {
Saqib61314242020-09-15 11:14:31 +0530547 fieldtype:'Link',
548 fieldname:'uom',
549 options: 'UOM',
550 read_only: 0,
551 label: __('UOM'),
552 reqd: 1,
553 onchange: function () {
554 frappe.call({
555 method: "erpnext.stock.get_item_details.get_conversion_factor",
556 args: { item_code: this.doc.item_code, uom: this.value },
557 callback: r => {
558 if(!r.exc) {
559 if (this.doc.conversion_factor == r.message.conversion_factor) return;
marination4f395cc2020-09-24 12:43:41 +0530560
Saqib61314242020-09-15 11:14:31 +0530561 const docname = this.doc.docname;
562 dialog.fields_dict.trans_items.df.data.some(doc => {
563 if (doc.docname == docname) {
564 doc.conversion_factor = r.message.conversion_factor;
565 dialog.fields_dict.trans_items.grid.refresh();
566 return true;
567 }
568 })
569 }
570 }
571 });
572 }
573 }, {
Saqib Ansarif53299e2020-04-15 22:08:12 +0530574 fieldtype:'Float',
575 fieldname:"qty",
576 default: 0,
577 read_only: 0,
578 in_list_view: 1,
Saqib56fea7d2020-10-09 21:19:25 +0530579 label: __('Qty'),
580 precision: get_precision("qty")
Saqib Ansarif53299e2020-04-15 22:08:12 +0530581 }, {
582 fieldtype:'Currency',
583 fieldname:"rate",
Afshan84184552021-02-24 16:51:11 +0530584 options: "currency",
Saqib Ansarif53299e2020-04-15 22:08:12 +0530585 default: 0,
586 read_only: 0,
587 in_list_view: 1,
Saqib56fea7d2020-10-09 21:19:25 +0530588 label: __('Rate'),
589 precision: get_precision("rate")
Saqib Ansarif53299e2020-04-15 22:08:12 +0530590 }];
591
592 if (frm.doc.doctype == 'Sales Order' || frm.doc.doctype == 'Purchase Order' ) {
593 fields.splice(2, 0, {
594 fieldtype: 'Date',
595 fieldname: frm.doc.doctype == 'Sales Order' ? "delivery_date" : "schedule_date",
596 in_list_view: 1,
Saqib Ansaric579b082020-05-29 22:21:50 +0530597 label: frm.doc.doctype == 'Sales Order' ? __("Delivery Date") : __("Reqd by date"),
598 reqd: 1
Saqib Ansarif53299e2020-04-15 22:08:12 +0530599 })
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +0530600 fields.splice(3, 0, {
601 fieldtype: 'Float',
602 fieldname: "conversion_factor",
603 in_list_view: 1,
Saqib56fea7d2020-10-09 21:19:25 +0530604 label: __("Conversion Factor"),
605 precision: get_precision('conversion_factor')
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +0530606 })
Saqib Ansarif53299e2020-04-15 22:08:12 +0530607 }
608
Devin Slauenwhitea835c1a2023-01-26 16:53:05 -0500609 new frappe.ui.Dialog({
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800610 title: __("Update Items"),
611 fields: [
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800612 {
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +0100613 fieldname: "trans_items",
614 fieldtype: "Table",
Maricafc96c1a2020-03-06 10:57:59 +0530615 label: "Items",
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +0100616 cannot_add_rows: cannot_add_row,
Saqibbc919e22020-11-05 17:38:35 +0530617 in_place_edit: false,
Maricafc96c1a2020-03-06 10:57:59 +0530618 reqd: 1,
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +0100619 data: this.data,
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800620 get_data: () => {
621 return this.data;
622 },
Saqib Ansarif53299e2020-04-15 22:08:12 +0530623 fields: fields
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800624 },
625 ],
626 primary_action: function() {
Ankush Menat6de7b8e2021-08-24 12:18:40 +0530627 const trans_items = this.get_values()["trans_items"].filter((item) => !!item.item_code);
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800628 frappe.call({
629 method: 'erpnext.controllers.accounts_controller.update_child_qty_rate',
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +0100630 freeze: true,
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800631 args: {
632 'parent_doctype': frm.doc.doctype,
633 'trans_items': trans_items,
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +0100634 'parent_doctype_name': frm.doc.name,
635 'child_docname': child_docname
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800636 },
637 callback: function() {
638 frm.reload_doc();
639 }
640 });
641 this.hide();
642 refresh_field("items");
643 },
644 primary_action_label: __('Update')
Devin Slauenwhitea835c1a2023-01-26 16:53:05 -0500645 }).show();
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800646}
647
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530648erpnext.utils.map_current_doc = function(opts) {
Sagar Vora78777d62021-03-09 20:35:08 +0530649 function _map() {
Rushabh Mehta55ea7b12016-07-15 16:43:25 +0530650 if($.isArray(cur_frm.doc.items) && cur_frm.doc.items.length > 0) {
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530651 // remove first item row if empty
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530652 if(!cur_frm.doc.items[0].item_code) {
653 cur_frm.doc.items = cur_frm.doc.items.splice(1);
654 }
bhupen3c7e70f2016-11-30 14:32:11 +0530655
656 // find the doctype of the items table
657 var items_doctype = frappe.meta.get_docfield(cur_frm.doctype, 'items').options;
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530658
bhupen3c7e70f2016-11-30 14:32:11 +0530659 // find the link fieldname from items table for the given
660 // source_doctype
661 var link_fieldname = null;
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530662 frappe.get_meta(items_doctype).fields.forEach(function(d) {
bhupen3c7e70f2016-11-30 14:32:11 +0530663 if(d.options===opts.source_doctype) link_fieldname = d.fieldname; });
664
Nabin Hait802b4352017-01-09 15:32:20 +0530665 // search in existing items if the source_name is already set and full qty fetched
bhupen3c7e70f2016-11-30 14:32:11 +0530666 var already_set = false;
Nabin Hait802b4352017-01-09 15:32:20 +0530667 var item_qty_map = {};
bhupen3c7e70f2016-11-30 14:32:11 +0530668
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530669 $.each(cur_frm.doc.items, function(i, d) {
670 opts.source_name.forEach(function(src) {
671 if(d[link_fieldname]==src) {
672 already_set = true;
673 if (item_qty_map[d.item_code])
674 item_qty_map[d.item_code] += flt(d.qty);
675 else
676 item_qty_map[d.item_code] = flt(d.qty);
677 }
678 });
679 });
680
681 if(already_set) {
682 opts.source_name.forEach(function(src) {
683 frappe.model.with_doc(opts.source_doctype, src, function(r) {
684 var source_doc = frappe.model.get_doc(opts.source_doctype, src);
685 $.each(source_doc.items || [], function(i, row) {
686 if(row.qty > flt(item_qty_map[row.item_code])) {
687 already_set = false;
688 return false;
689 }
690 })
691 })
692
693 if(already_set) {
694 frappe.msgprint(__("You have already selected items from {0} {1}",
695 [opts.source_doctype, src]));
696 return;
697 }
698
699 })
Nabin Hait802b4352017-01-09 15:32:20 +0530700 }
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530701 }
702
703 return frappe.call({
704 // Sometimes we hit the limit for URL length of a GET request
705 // as we send the full target_doc. Hence this is a POST request.
706 type: "POST",
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530707 method: 'frappe.model.mapper.map_docs',
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530708 args: {
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530709 "method": opts.method,
710 "source_names": opts.source_name,
711 "target_doc": cur_frm.doc,
Maricadb002702020-02-17 15:58:08 +0530712 "args": opts.args
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530713 },
714 callback: function(r) {
715 if(!r.exc) {
716 var doc = frappe.model.sync(r.message);
Vishal Dhayagudef06c2812017-12-26 16:22:40 +0530717 cur_frm.dirty();
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530718 cur_frm.refresh();
719 }
720 }
721 });
722 }
Sagar Vora78777d62021-03-09 20:35:08 +0530723
724 let query_args = {};
725 if (opts.get_query_filters) {
726 query_args.filters = opts.get_query_filters;
727 }
728
729 if (opts.get_query_method) {
730 query_args.query = opts.get_query_method;
731 }
732
733 if (query_args.filters || query_args.query) {
734 opts.get_query = () => query_args;
735 }
736
737 if (opts.source_doctype) {
738 const d = new frappe.ui.form.MultiSelectDialog({
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530739 doctype: opts.source_doctype,
740 target: opts.target,
741 date_field: opts.date_field || undefined,
742 setters: opts.setters,
743 get_query: opts.get_query,
marination4f395cc2020-09-24 12:43:41 +0530744 add_filters_group: 1,
Saqib7292f542021-09-13 12:13:43 +0530745 allow_child_item_selection: opts.allow_child_item_selection,
gn3060292a619fd2022-06-29 17:15:21 +0800746 child_fieldname: opts.child_fieldname,
Saqib7292f542021-09-13 12:13:43 +0530747 child_columns: opts.child_columns,
Rohit Waghchaure69ffddf2021-10-07 17:33:58 +0530748 size: opts.size,
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530749 action: function(selections, args) {
750 let values = selections;
Saqibe03d9aa2021-09-17 13:03:27 +0530751 if (values.length === 0) {
Nabin Haita11dcb62017-12-04 13:36:50 +0530752 frappe.msgprint(__("Please select {0}", [opts.source_doctype]))
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530753 return;
754 }
755 opts.source_name = values;
Saqibe03d9aa2021-09-17 13:03:27 +0530756 if (opts.allow_child_item_selection) {
757 // args contains filtered child docnames
758 opts.args = args;
759 }
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530760 d.dialog.hide();
761 _map();
762 },
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530763 });
Sagar Vora78777d62021-03-09 20:35:08 +0530764
765 return d;
766 }
767
768 if (opts.source_name) {
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530769 opts.source_name = [opts.source_name];
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530770 _map();
771 }
772}
773
Rushabh Mehta180e4352016-07-26 17:57:42 +0530774frappe.form.link_formatters['Item'] = function(value, doc) {
Alan157b3882021-04-21 21:00:22 +0530775 if (doc && value && doc.item_name && doc.item_name !== value && doc.item_code === value) {
marination824f48f2020-10-12 20:08:03 +0530776 return value + ': ' + doc.item_name;
777 } else if (!value && doc.doctype && doc.item_name) {
778 // format blank value in child table
779 return doc.item_name;
Rushabh Mehta180e4352016-07-26 17:57:42 +0530780 } else {
marination824f48f2020-10-12 20:08:03 +0530781 // 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 +0530782 return value;
783 }
784}
785
786frappe.form.link_formatters['Employee'] = function(value, doc) {
Rucha Mahabal5ba1bc12021-11-23 09:30:30 +0530787 if (doc && value && doc.employee_name && doc.employee_name !== value && doc.employee === value) {
788 return value + ': ' + doc.employee_name;
789 } else if (!value && doc.doctype && doc.employee_name) {
790 // format blank value in child table
791 return doc.employee;
Rushabh Mehta180e4352016-07-26 17:57:42 +0530792 } else {
Rucha Mahabal5ba1bc12021-11-23 09:30:30 +0530793 // 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 +0530794 return value;
795 }
796}
797
Rucha Mahabal59961f72021-05-20 23:43:19 +0530798frappe.form.link_formatters['Project'] = function(value, doc) {
799 if (doc && value && doc.project_name && doc.project_name !== value && doc.project === value) {
800 return value + ': ' + doc.project_name;
801 } else if (!value && doc.doctype && doc.project_name) {
802 // format blank value in child table
803 return doc.project;
804 } else {
805 // if value is blank in report view or project name and name are the same, return as is
806 return value;
807 }
808};
809
Rushabh Mehta95b995b2015-05-28 12:10:55 +0530810// add description on posting time
811$(document).on('app_ready', function() {
812 if(!frappe.datetime.is_timezone_same()) {
813 $.each(["Stock Reconciliation", "Stock Entry", "Stock Ledger Entry",
814 "Delivery Note", "Purchase Receipt", "Sales Invoice"], function(i, d) {
815 frappe.ui.form.on(d, "onload", function(frm) {
816 cur_frm.set_df_property("posting_time", "description",
Faris Ansariab74ca72017-05-30 12:54:42 +0530817 frappe.sys_defaults.time_zone);
Rushabh Mehta95b995b2015-05-28 12:10:55 +0530818 });
819 });
820 }
akshay14384c22016-07-28 13:53:17 +0530821});
Alanc6dc9ea2021-05-07 20:30:04 +0530822
Himanshuec25d592021-06-14 19:05:52 +0530823// Show SLA dashboard
824$(document).on('app_ready', function() {
825 frappe.call({
826 method: 'erpnext.support.doctype.service_level_agreement.service_level_agreement.get_sla_doctypes',
827 callback: function(r) {
828 if (!r.message)
829 return;
830
831 $.each(r.message, function(_i, d) {
832 frappe.ui.form.on(d, {
833 onload: function(frm) {
834 if (!frm.doc.service_level_agreement)
835 return;
836
837 frappe.call({
838 method: 'erpnext.support.doctype.service_level_agreement.service_level_agreement.get_service_level_agreement_filters',
839 args: {
840 doctype: frm.doc.doctype,
841 name: frm.doc.service_level_agreement,
842 customer: frm.doc.customer
843 },
844 callback: function (r) {
845 if (r && r.message) {
846 frm.set_query('priority', function() {
847 return {
848 filters: {
849 'name': ['in', r.message.priority],
850 }
851 };
852 });
853 frm.set_query('service_level_agreement', function() {
854 return {
855 filters: {
856 'name': ['in', r.message.service_level_agreements],
857 }
858 };
859 });
860 }
861 }
862 });
863 },
864
865 refresh: function(frm) {
866 if (frm.doc.status !== 'Closed' && frm.doc.service_level_agreement
Saqib Ansari476e81a2021-12-06 18:55:30 +0530867 && ['First Response Due', 'Resolution Due'].includes(frm.doc.agreement_status)) {
Himanshuec25d592021-06-14 19:05:52 +0530868 frappe.call({
869 'method': 'frappe.client.get',
870 args: {
871 doctype: 'Service Level Agreement',
872 name: frm.doc.service_level_agreement
873 },
874 callback: function(data) {
875 let statuses = data.message.pause_sla_on;
876 const hold_statuses = [];
877 $.each(statuses, (_i, entry) => {
878 hold_statuses.push(entry.status);
879 });
880 if (hold_statuses.includes(frm.doc.status)) {
881 frm.dashboard.clear_headline();
882 let message = {'indicator': 'orange', 'msg': __('SLA is on hold since {0}', [moment(frm.doc.on_hold_since).fromNow(true)])};
883 frm.dashboard.set_headline_alert(
884 '<div class="row">' +
885 '<div class="col-xs-12">' +
886 '<span class="indicator whitespace-nowrap '+ message.indicator +'"><span>'+ message.msg +'</span></span> ' +
887 '</div>' +
888 '</div>'
889 );
890 } else {
891 set_time_to_resolve_and_response(frm, data.message.apply_sla_for_resolution);
892 }
893 }
894 });
895 } else if (frm.doc.service_level_agreement) {
896 frm.dashboard.clear_headline();
897
898 let agreement_status = (frm.doc.agreement_status == 'Fulfilled') ?
899 {'indicator': 'green', 'msg': 'Service Level Agreement has been fulfilled'} :
900 {'indicator': 'red', 'msg': 'Service Level Agreement Failed'};
901
902 frm.dashboard.set_headline_alert(
903 '<div class="row">' +
904 '<div class="col-xs-12">' +
905 '<span class="indicator whitespace-nowrap '+ agreement_status.indicator +'"><span class="hidden-xs">'+ agreement_status.msg +'</span></span> ' +
906 '</div>' +
907 '</div>'
908 );
909 }
910 },
911 });
912 });
913 }
914 });
915});
916
917function set_time_to_resolve_and_response(frm, apply_sla_for_resolution) {
918 frm.dashboard.clear_headline();
919
Saqib24114772021-12-15 11:45:34 +0530920 let time_to_respond;
Saqib Ansari476e81a2021-12-06 18:55:30 +0530921 if (!frm.doc.first_responded_on) {
Himanshuec25d592021-06-14 19:05:52 +0530922 time_to_respond = get_time_left(frm.doc.response_by, frm.doc.agreement_status);
Saqib24114772021-12-15 11:45:34 +0530923 } else {
924 time_to_respond = get_status(frm.doc.response_by, frm.doc.first_responded_on);
Himanshuec25d592021-06-14 19:05:52 +0530925 }
926
927 let alert = `
928 <div class="row">
929 <div class="col-xs-12 col-sm-6">
930 <span class="indicator whitespace-nowrap ${time_to_respond.indicator}">
931 <span>Time to Respond: ${time_to_respond.diff_display}</span>
932 </span>
933 </div>`;
934
935
936 if (apply_sla_for_resolution) {
Saqib24114772021-12-15 11:45:34 +0530937 let time_to_resolve;
Saqib Ansari476e81a2021-12-06 18:55:30 +0530938 if (!frm.doc.resolution_date) {
Himanshuec25d592021-06-14 19:05:52 +0530939 time_to_resolve = get_time_left(frm.doc.resolution_by, frm.doc.agreement_status);
Saqib24114772021-12-15 11:45:34 +0530940 } else {
941 time_to_resolve = get_status(frm.doc.resolution_by, frm.doc.resolution_date);
Himanshuec25d592021-06-14 19:05:52 +0530942 }
943
944 alert += `
945 <div class="col-xs-12 col-sm-6">
946 <span class="indicator whitespace-nowrap ${time_to_resolve.indicator}">
947 <span>Time to Resolve: ${time_to_resolve.diff_display}</span>
948 </span>
949 </div>`;
950 }
951
952 alert += '</div>';
953
954 frm.dashboard.set_headline_alert(alert);
955}
956
957function get_time_left(timestamp, agreement_status) {
958 const diff = moment(timestamp).diff(moment());
959 const diff_display = diff >= 44500 ? moment.duration(diff).humanize() : 'Failed';
960 let indicator = (diff_display == 'Failed' && agreement_status != 'Fulfilled') ? 'red' : 'green';
961 return {'diff_display': diff_display, 'indicator': indicator};
962}
963
Saqib24114772021-12-15 11:45:34 +0530964function get_status(expected, actual) {
965 const time_left = moment(expected).diff(moment(actual));
Saqib Ansari476e81a2021-12-06 18:55:30 +0530966 if (time_left >= 0) {
Himanshuec25d592021-06-14 19:05:52 +0530967 return {'diff_display': 'Fulfilled', 'indicator': 'green'};
968 } else {
969 return {'diff_display': 'Failed', 'indicator': 'red'};
970 }
971}
972
Alanc6dc9ea2021-05-07 20:30:04 +0530973function attach_selector_button(inner_text, append_loction, context, grid_row) {
974 let $btn_div = $("<div>").css({"margin-bottom": "10px", "margin-top": "10px"})
975 .appendTo(append_loction);
976 let $btn = $(`<button class="btn btn-sm btn-default">${inner_text}</button>`)
977 .appendTo($btn_div);
978
979 $btn.on("click", function() {
980 context.show_serial_batch_selector(grid_row.frm, grid_row.doc, "", "", true);
981 });
982}