blob: d37b7bb43b38b243c14dc1573823513d3ebef85d [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) => {
224 let found = filters.some(el => el.fieldname === dimension['fieldname']);
225
226 if (!found) {
227 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 });
235 }
236 });
237 }
238 }
239 });
240 },
241
rohitwaghchaure166b78f2017-09-07 16:14:22 +0530242 make_subscription: function(doctype, docname) {
243 frappe.call({
Rucha Mahabal65a627c2019-07-17 13:50:32 +0530244 method: "frappe.automation.doctype.auto_repeat.auto_repeat.make_auto_repeat",
rohitwaghchaure166b78f2017-09-07 16:14:22 +0530245 args: {
246 doctype: doctype,
247 docname: docname
248 },
249 callback: function(r) {
250 var doclist = frappe.model.sync(r.message);
251 frappe.set_route("Form", doclist[0].doctype, doclist[0].name);
252 }
253 })
254 },
255
Saif90cf2dd2018-09-30 21:46:31 +0500256 make_pricing_rule: function(doctype, docname) {
257 frappe.call({
258 method: "erpnext.accounts.doctype.pricing_rule.pricing_rule.make_pricing_rule",
259 args: {
260 doctype: doctype,
261 docname: docname
262 },
263 callback: function(r) {
264 var doclist = frappe.model.sync(r.message);
265 frappe.set_route("Form", doclist[0].doctype, doclist[0].name);
266 }
267 })
268 },
269
tundebabzy1a947db2017-08-29 13:48:27 +0100270 /**
271 * Checks if the first row of a given child table is empty
272 * @param child_table - Child table Doctype
273 * @return {Boolean}
274 **/
275 first_row_is_empty: function(child_table){
276 if($.isArray(child_table) && child_table.length > 0) {
277 return !child_table[0].item_code;
278 }
279 return false;
280 },
281
282 /**
283 * Removes the first row of a child table if it is empty
284 * @param {_Frm} frm - The current form
285 * @param {String} child_table_name - The child table field name
286 * @return {Boolean}
287 **/
288 remove_empty_first_row: function(frm, child_table_name){
289 const rows = frm['doc'][child_table_name];
290 if (this.first_row_is_empty(rows)){
291 frm['doc'][child_table_name] = rows.splice(1);
292 }
293 return rows;
294 },
Zarrar6ffdf942018-06-14 12:24:16 +0530295 get_tree_options: function(option) {
296 // get valid options for tree based on user permission & locals dict
297 let unscrub_option = frappe.model.unscrub(option);
298 let user_permission = frappe.defaults.get_user_permissions();
deepeshgarg0070d64d622019-02-20 17:55:14 +0530299 let options;
300
Zarrar6ffdf942018-06-14 12:24:16 +0530301 if(user_permission && user_permission[unscrub_option]) {
deepeshgarg0070d64d622019-02-20 17:55:14 +0530302 options = user_permission[unscrub_option].map(perm => perm.doc);
Zarrar6ffdf942018-06-14 12:24:16 +0530303 } else {
deepeshgarg0070d64d622019-02-20 17:55:14 +0530304 options = $.map(locals[`:${unscrub_option}`], function(c) { return c.name; }).sort();
Zarrar6ffdf942018-06-14 12:24:16 +0530305 }
deepeshgarg0070d64d622019-02-20 17:55:14 +0530306
307 // filter unique values, as there may be multiple user permissions for any value
308 return options.filter((value, index, self) => self.indexOf(value) === index);
Zarrar6ffdf942018-06-14 12:24:16 +0530309 },
310 get_tree_default: function(option) {
311 // set default for a field based on user permission
312 let options = this.get_tree_options(option);
313 if(options.includes(frappe.defaults.get_default(option))) {
314 return frappe.defaults.get_default(option);
315 } else {
316 return options[0];
317 }
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400318 },
Andy Zhubffe9332021-04-12 22:49:26 +1200319 overrides_parent_value_in_all_rows: function(doc, dt, dn, table_fieldname, fieldname, parent_fieldname) {
Marica24e45162021-04-14 18:53:15 +0530320 if (doc[parent_fieldname]) {
Andy Zhubffe9332021-04-12 22:49:26 +1200321 let cl = doc[table_fieldname] || [];
Marica24e45162021-04-14 18:53:15 +0530322 for (let i = 0; i < cl.length; i++) {
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400323 cl[i][fieldname] = doc[parent_fieldname];
324 }
Andy Zhubffe9332021-04-12 22:49:26 +1200325 frappe.refresh_field(table_fieldname);
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400326 }
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400327 },
Nabin Hait34c551d2019-07-03 10:34:31 +0530328 create_new_doc: function (doctype, update_fields) {
329 frappe.model.with_doctype(doctype, function() {
330 var new_doc = frappe.model.get_new_doc(doctype);
331 for (let [key, value] of Object.entries(update_fields)) {
332 new_doc[key] = value;
333 }
334 frappe.ui.form.make_quick_entry(doctype, null, null, new_doc);
335 });
Ankush Menat0b86b1b2022-12-08 16:40:13 +0530336 },
Nabin Hait34c551d2019-07-03 10:34:31 +0530337
Ankush Menat0b86b1b2022-12-08 16:40:13 +0530338 // check if payments app is installed on site, if not warn user.
339 check_payments_app: () => {
340 if (frappe.boot.versions && !frappe.boot.versions.payments) {
341 const marketplace_link = '<a href="https://frappecloud.com/marketplace/apps/payments">Marketplace</a>'
342 const github_link = '<a href="https://github.com/frappe/payments/">GitHub</a>'
343 const msg = __("payments app is not installed. Please install it from {0} or {1}", [marketplace_link, github_link])
344 frappe.msgprint(msg);
345 }
346
347 },
Rushabh Mehta95b995b2015-05-28 12:10:55 +0530348});
349
rohitwaghchaurea3c3dec2018-03-28 11:51:44 +0530350erpnext.utils.select_alternate_items = function(opts) {
351 const frm = opts.frm;
352 const warehouse_field = opts.warehouse_field || 'warehouse';
353 const item_field = opts.item_field || 'item_code';
354
355 this.data = [];
356 const dialog = new frappe.ui.Dialog({
357 title: __("Select Alternate Item"),
358 fields: [
359 {fieldtype:'Section Break', label: __('Items')},
360 {
361 fieldname: "alternative_items", fieldtype: "Table", cannot_add_rows: true,
362 in_place_edit: true, data: this.data,
363 get_data: () => {
364 return this.data;
365 },
366 fields: [{
367 fieldtype:'Data',
368 fieldname:"docname",
369 hidden: 1
370 }, {
371 fieldtype:'Link',
372 fieldname:"item_code",
373 options: 'Item',
374 in_list_view: 1,
375 read_only: 1,
376 label: __('Item Code')
377 }, {
378 fieldtype:'Link',
379 fieldname:"alternate_item",
380 options: 'Item',
381 default: "",
382 in_list_view: 1,
383 label: __('Alternate Item'),
384 onchange: function() {
385 const item_code = this.get_value();
386 const warehouse = this.grid_row.on_grid_fields_dict.warehouse.get_value();
387 if (item_code && warehouse) {
388 frappe.call({
389 method: "erpnext.stock.utils.get_latest_stock_qty",
390 args: {
391 item_code: item_code,
392 warehouse: warehouse
393 },
394 callback: (r) => {
395 this.grid_row.on_grid_fields_dict
396 .actual_qty.set_value(r.message || 0);
397 }
398 })
399 }
400 },
401 get_query: (e) => {
402 return {
403 query: "erpnext.stock.doctype.item_alternative.item_alternative.get_alternative_items",
404 filters: {
405 item_code: e.item_code
406 }
407 };
408 }
409 }, {
410 fieldtype:'Link',
411 fieldname:"warehouse",
412 options: 'Warehouse',
413 default: "",
414 in_list_view: 1,
415 label: __('Warehouse'),
416 onchange: function() {
417 const warehouse = this.get_value();
418 const item_code = this.grid_row.on_grid_fields_dict.item_code.get_value();
419 if (item_code && warehouse) {
420 frappe.call({
421 method: "erpnext.stock.utils.get_latest_stock_qty",
422 args: {
423 item_code: item_code,
424 warehouse: warehouse
425 },
426 callback: (r) => {
427 this.grid_row.on_grid_fields_dict
428 .actual_qty.set_value(r.message || 0);
429 }
430 })
431 }
432 },
433 }, {
434 fieldtype:'Float',
435 fieldname:"actual_qty",
436 default: 0,
437 read_only: 1,
438 in_list_view: 1,
439 label: __('Available Qty')
440 }]
441 },
442 ],
443 primary_action: function() {
444 const args = this.get_values()["alternative_items"];
445 const alternative_items = args.filter(d => {
446 if (d.alternate_item && d.item_code != d.alternate_item) {
447 return true;
448 }
449 });
450
451 alternative_items.forEach(d => {
452 let row = frappe.get_doc(opts.child_doctype, d.docname);
Doridel Cahanape42192b2018-05-16 13:28:39 +0800453 let qty = null;
454 if (row.doctype === 'Work Order Item') {
455 qty = row.required_qty;
456 } else {
457 qty = row.qty;
458 }
rohitwaghchaurea3c3dec2018-03-28 11:51:44 +0530459 row[item_field] = d.alternate_item;
mergify[bot]c1a0f642021-12-17 19:06:19 +0530460 frappe.model.set_value(row.doctype, row.name, 'qty', qty);
461 frappe.model.set_value(row.doctype, row.name, opts.original_item_field, d.item_code);
462 frm.trigger(item_field, row.doctype, row.name);
rohitwaghchaurea3c3dec2018-03-28 11:51:44 +0530463 });
464
465 refresh_field(opts.child_docname);
466 this.hide();
467 },
468 primary_action_label: __('Update')
469 });
470
471 frm.doc[opts.child_docname].forEach(d => {
472 if (!opts.condition || opts.condition(d)) {
473 dialog.fields_dict.alternative_items.df.data.push({
474 "docname": d.name,
475 "item_code": d[item_field],
476 "warehouse": d[warehouse_field],
477 "actual_qty": d.actual_qty
478 });
479 }
480 })
481
482 this.data = dialog.fields_dict.alternative_items.df.data;
483 dialog.fields_dict.alternative_items.grid.refresh();
484 dialog.show();
485}
486
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800487erpnext.utils.update_child_items = function(opts) {
488 const frm = opts.frm;
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +0100489 const cannot_add_row = (typeof opts.cannot_add_row === 'undefined') ? true : opts.cannot_add_row;
490 const child_docname = (typeof opts.cannot_add_row === 'undefined') ? "items" : opts.child_docname;
Saqib56fea7d2020-10-09 21:19:25 +0530491 const child_meta = frappe.get_meta(`${frm.doc.doctype} Item`);
492 const get_precision = (fieldname) => child_meta.fields.find(f => f.fieldname == fieldname).precision;
493
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800494 this.data = [];
Saqib Ansarif53299e2020-04-15 22:08:12 +0530495 const fields = [{
496 fieldtype:'Data',
497 fieldname:"docname",
498 read_only: 1,
499 hidden: 1,
500 }, {
501 fieldtype:'Link',
502 fieldname:"item_code",
503 options: 'Item',
504 in_list_view: 1,
505 read_only: 0,
506 disabled: 0,
Afshandc7280e2021-08-18 17:44:40 +0530507 label: __('Item Code'),
508 get_query: function() {
509 let filters;
510 if (frm.doc.doctype == 'Sales Order') {
511 filters = {"is_sales_item": 1};
512 } else if (frm.doc.doctype == 'Purchase Order') {
Sagar Sharmad074c932022-03-31 19:57:42 +0530513 if (frm.doc.is_subcontracted) {
s-aga-r6d89b2f2022-06-18 15:46:59 +0530514 if (frm.doc.is_old_subcontracting_flow) {
515 filters = {"is_sub_contracted_item": 1};
516 } else {
517 filters = {"is_stock_item": 0};
518 }
Afshandc7280e2021-08-18 17:44:40 +0530519 } else {
520 filters = {"is_purchase_item": 1};
521 }
522 }
523 return {
524 query: "erpnext.controllers.queries.item_query",
525 filters: filters
526 };
527 }
Saqib Ansarif53299e2020-04-15 22:08:12 +0530528 }, {
Saqib61314242020-09-15 11:14:31 +0530529 fieldtype:'Link',
530 fieldname:'uom',
531 options: 'UOM',
532 read_only: 0,
533 label: __('UOM'),
534 reqd: 1,
535 onchange: function () {
536 frappe.call({
537 method: "erpnext.stock.get_item_details.get_conversion_factor",
538 args: { item_code: this.doc.item_code, uom: this.value },
539 callback: r => {
540 if(!r.exc) {
541 if (this.doc.conversion_factor == r.message.conversion_factor) return;
marination4f395cc2020-09-24 12:43:41 +0530542
Saqib61314242020-09-15 11:14:31 +0530543 const docname = this.doc.docname;
544 dialog.fields_dict.trans_items.df.data.some(doc => {
545 if (doc.docname == docname) {
546 doc.conversion_factor = r.message.conversion_factor;
547 dialog.fields_dict.trans_items.grid.refresh();
548 return true;
549 }
550 })
551 }
552 }
553 });
554 }
555 }, {
Saqib Ansarif53299e2020-04-15 22:08:12 +0530556 fieldtype:'Float',
557 fieldname:"qty",
558 default: 0,
559 read_only: 0,
560 in_list_view: 1,
Saqib56fea7d2020-10-09 21:19:25 +0530561 label: __('Qty'),
562 precision: get_precision("qty")
Saqib Ansarif53299e2020-04-15 22:08:12 +0530563 }, {
564 fieldtype:'Currency',
565 fieldname:"rate",
Afshan84184552021-02-24 16:51:11 +0530566 options: "currency",
Saqib Ansarif53299e2020-04-15 22:08:12 +0530567 default: 0,
568 read_only: 0,
569 in_list_view: 1,
Saqib56fea7d2020-10-09 21:19:25 +0530570 label: __('Rate'),
571 precision: get_precision("rate")
Saqib Ansarif53299e2020-04-15 22:08:12 +0530572 }];
573
574 if (frm.doc.doctype == 'Sales Order' || frm.doc.doctype == 'Purchase Order' ) {
575 fields.splice(2, 0, {
576 fieldtype: 'Date',
577 fieldname: frm.doc.doctype == 'Sales Order' ? "delivery_date" : "schedule_date",
578 in_list_view: 1,
Saqib Ansaric579b082020-05-29 22:21:50 +0530579 label: frm.doc.doctype == 'Sales Order' ? __("Delivery Date") : __("Reqd by date"),
580 reqd: 1
Saqib Ansarif53299e2020-04-15 22:08:12 +0530581 })
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +0530582 fields.splice(3, 0, {
583 fieldtype: 'Float',
584 fieldname: "conversion_factor",
585 in_list_view: 1,
Saqib56fea7d2020-10-09 21:19:25 +0530586 label: __("Conversion Factor"),
587 precision: get_precision('conversion_factor')
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +0530588 })
Saqib Ansarif53299e2020-04-15 22:08:12 +0530589 }
590
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800591 const dialog = new frappe.ui.Dialog({
592 title: __("Update Items"),
593 fields: [
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800594 {
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +0100595 fieldname: "trans_items",
596 fieldtype: "Table",
Maricafc96c1a2020-03-06 10:57:59 +0530597 label: "Items",
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +0100598 cannot_add_rows: cannot_add_row,
Saqibbc919e22020-11-05 17:38:35 +0530599 in_place_edit: false,
Maricafc96c1a2020-03-06 10:57:59 +0530600 reqd: 1,
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +0100601 data: this.data,
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800602 get_data: () => {
603 return this.data;
604 },
Saqib Ansarif53299e2020-04-15 22:08:12 +0530605 fields: fields
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800606 },
607 ],
608 primary_action: function() {
Ankush Menat6de7b8e2021-08-24 12:18:40 +0530609 const trans_items = this.get_values()["trans_items"].filter((item) => !!item.item_code);
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800610 frappe.call({
611 method: 'erpnext.controllers.accounts_controller.update_child_qty_rate',
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +0100612 freeze: true,
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800613 args: {
614 'parent_doctype': frm.doc.doctype,
615 'trans_items': trans_items,
Stavros Anastasiadis3d82b742018-12-10 13:00:55 +0100616 'parent_doctype_name': frm.doc.name,
617 'child_docname': child_docname
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800618 },
619 callback: function() {
620 frm.reload_doc();
621 }
622 });
623 this.hide();
624 refresh_field("items");
625 },
626 primary_action_label: __('Update')
627 });
628
629 frm.doc[opts.child_docname].forEach(d => {
630 dialog.fields_dict.trans_items.df.data.push({
631 "docname": d.name,
Prssanna Desai4f72c0b2019-12-23 18:27:12 +0530632 "name": d.name,
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800633 "item_code": d.item_code,
Saqib Ansarif53299e2020-04-15 22:08:12 +0530634 "delivery_date": d.delivery_date,
635 "schedule_date": d.schedule_date,
Saqib Ansari2c3c8aa2020-05-29 21:55:38 +0530636 "conversion_factor": d.conversion_factor,
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800637 "qty": d.qty,
638 "rate": d.rate,
Saqib61314242020-09-15 11:14:31 +0530639 "uom": d.uom
Doridel Cahanap6f06cc22018-05-17 16:28:58 +0800640 });
641 this.data = dialog.fields_dict.trans_items.df.data;
642 dialog.fields_dict.trans_items.grid.refresh();
643 })
644 dialog.show();
645}
646
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530647erpnext.utils.map_current_doc = function(opts) {
Sagar Vora78777d62021-03-09 20:35:08 +0530648 function _map() {
Rushabh Mehta55ea7b12016-07-15 16:43:25 +0530649 if($.isArray(cur_frm.doc.items) && cur_frm.doc.items.length > 0) {
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530650 // remove first item row if empty
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530651 if(!cur_frm.doc.items[0].item_code) {
652 cur_frm.doc.items = cur_frm.doc.items.splice(1);
653 }
bhupen3c7e70f2016-11-30 14:32:11 +0530654
655 // find the doctype of the items table
656 var items_doctype = frappe.meta.get_docfield(cur_frm.doctype, 'items').options;
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530657
bhupen3c7e70f2016-11-30 14:32:11 +0530658 // find the link fieldname from items table for the given
659 // source_doctype
660 var link_fieldname = null;
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530661 frappe.get_meta(items_doctype).fields.forEach(function(d) {
bhupen3c7e70f2016-11-30 14:32:11 +0530662 if(d.options===opts.source_doctype) link_fieldname = d.fieldname; });
663
Nabin Hait802b4352017-01-09 15:32:20 +0530664 // search in existing items if the source_name is already set and full qty fetched
bhupen3c7e70f2016-11-30 14:32:11 +0530665 var already_set = false;
Nabin Hait802b4352017-01-09 15:32:20 +0530666 var item_qty_map = {};
bhupen3c7e70f2016-11-30 14:32:11 +0530667
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530668 $.each(cur_frm.doc.items, function(i, d) {
669 opts.source_name.forEach(function(src) {
670 if(d[link_fieldname]==src) {
671 already_set = true;
672 if (item_qty_map[d.item_code])
673 item_qty_map[d.item_code] += flt(d.qty);
674 else
675 item_qty_map[d.item_code] = flt(d.qty);
676 }
677 });
678 });
679
680 if(already_set) {
681 opts.source_name.forEach(function(src) {
682 frappe.model.with_doc(opts.source_doctype, src, function(r) {
683 var source_doc = frappe.model.get_doc(opts.source_doctype, src);
684 $.each(source_doc.items || [], function(i, row) {
685 if(row.qty > flt(item_qty_map[row.item_code])) {
686 already_set = false;
687 return false;
688 }
689 })
690 })
691
692 if(already_set) {
693 frappe.msgprint(__("You have already selected items from {0} {1}",
694 [opts.source_doctype, src]));
695 return;
696 }
697
698 })
Nabin Hait802b4352017-01-09 15:32:20 +0530699 }
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530700 }
701
702 return frappe.call({
703 // Sometimes we hit the limit for URL length of a GET request
704 // as we send the full target_doc. Hence this is a POST request.
705 type: "POST",
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530706 method: 'frappe.model.mapper.map_docs',
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530707 args: {
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530708 "method": opts.method,
709 "source_names": opts.source_name,
710 "target_doc": cur_frm.doc,
Maricadb002702020-02-17 15:58:08 +0530711 "args": opts.args
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530712 },
713 callback: function(r) {
714 if(!r.exc) {
715 var doc = frappe.model.sync(r.message);
Vishal Dhayagudef06c2812017-12-26 16:22:40 +0530716 cur_frm.dirty();
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530717 cur_frm.refresh();
718 }
719 }
720 });
721 }
Sagar Vora78777d62021-03-09 20:35:08 +0530722
723 let query_args = {};
724 if (opts.get_query_filters) {
725 query_args.filters = opts.get_query_filters;
726 }
727
728 if (opts.get_query_method) {
729 query_args.query = opts.get_query_method;
730 }
731
732 if (query_args.filters || query_args.query) {
733 opts.get_query = () => query_args;
734 }
735
736 if (opts.source_doctype) {
737 const d = new frappe.ui.form.MultiSelectDialog({
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530738 doctype: opts.source_doctype,
739 target: opts.target,
740 date_field: opts.date_field || undefined,
741 setters: opts.setters,
742 get_query: opts.get_query,
marination4f395cc2020-09-24 12:43:41 +0530743 add_filters_group: 1,
Saqib7292f542021-09-13 12:13:43 +0530744 allow_child_item_selection: opts.allow_child_item_selection,
gn3060292a619fd2022-06-29 17:15:21 +0800745 child_fieldname: opts.child_fieldname,
Saqib7292f542021-09-13 12:13:43 +0530746 child_columns: opts.child_columns,
Rohit Waghchaure69ffddf2021-10-07 17:33:58 +0530747 size: opts.size,
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530748 action: function(selections, args) {
749 let values = selections;
Saqibe03d9aa2021-09-17 13:03:27 +0530750 if (values.length === 0) {
Nabin Haita11dcb62017-12-04 13:36:50 +0530751 frappe.msgprint(__("Please select {0}", [opts.source_doctype]))
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530752 return;
753 }
754 opts.source_name = values;
Saqibe03d9aa2021-09-17 13:03:27 +0530755 if (opts.allow_child_item_selection) {
756 // args contains filtered child docnames
757 opts.args = args;
758 }
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530759 d.dialog.hide();
760 _map();
761 },
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530762 });
Sagar Vora78777d62021-03-09 20:35:08 +0530763
764 return d;
765 }
766
767 if (opts.source_name) {
Prateeksha Singhedeb4dc2017-05-15 11:32:06 +0530768 opts.source_name = [opts.source_name];
Rushabh Mehta176b63b2016-07-14 17:43:48 +0530769 _map();
770 }
771}
772
Rushabh Mehta180e4352016-07-26 17:57:42 +0530773frappe.form.link_formatters['Item'] = function(value, doc) {
Alan157b3882021-04-21 21:00:22 +0530774 if (doc && value && doc.item_name && doc.item_name !== value && doc.item_code === value) {
marination824f48f2020-10-12 20:08:03 +0530775 return value + ': ' + doc.item_name;
776 } else if (!value && doc.doctype && doc.item_name) {
777 // format blank value in child table
778 return doc.item_name;
Rushabh Mehta180e4352016-07-26 17:57:42 +0530779 } else {
marination824f48f2020-10-12 20:08:03 +0530780 // 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 +0530781 return value;
782 }
783}
784
785frappe.form.link_formatters['Employee'] = function(value, doc) {
Rucha Mahabal5ba1bc12021-11-23 09:30:30 +0530786 if (doc && value && doc.employee_name && doc.employee_name !== value && doc.employee === value) {
787 return value + ': ' + doc.employee_name;
788 } else if (!value && doc.doctype && doc.employee_name) {
789 // format blank value in child table
790 return doc.employee;
Rushabh Mehta180e4352016-07-26 17:57:42 +0530791 } else {
Rucha Mahabal5ba1bc12021-11-23 09:30:30 +0530792 // 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 +0530793 return value;
794 }
795}
796
Rucha Mahabal59961f72021-05-20 23:43:19 +0530797frappe.form.link_formatters['Project'] = function(value, doc) {
798 if (doc && value && doc.project_name && doc.project_name !== value && doc.project === value) {
799 return value + ': ' + doc.project_name;
800 } else if (!value && doc.doctype && doc.project_name) {
801 // format blank value in child table
802 return doc.project;
803 } else {
804 // if value is blank in report view or project name and name are the same, return as is
805 return value;
806 }
807};
808
Rushabh Mehta95b995b2015-05-28 12:10:55 +0530809// add description on posting time
810$(document).on('app_ready', function() {
811 if(!frappe.datetime.is_timezone_same()) {
812 $.each(["Stock Reconciliation", "Stock Entry", "Stock Ledger Entry",
813 "Delivery Note", "Purchase Receipt", "Sales Invoice"], function(i, d) {
814 frappe.ui.form.on(d, "onload", function(frm) {
815 cur_frm.set_df_property("posting_time", "description",
Faris Ansariab74ca72017-05-30 12:54:42 +0530816 frappe.sys_defaults.time_zone);
Rushabh Mehta95b995b2015-05-28 12:10:55 +0530817 });
818 });
819 }
akshay14384c22016-07-28 13:53:17 +0530820});
Alanc6dc9ea2021-05-07 20:30:04 +0530821
Himanshuec25d592021-06-14 19:05:52 +0530822// Show SLA dashboard
823$(document).on('app_ready', function() {
824 frappe.call({
825 method: 'erpnext.support.doctype.service_level_agreement.service_level_agreement.get_sla_doctypes',
826 callback: function(r) {
827 if (!r.message)
828 return;
829
830 $.each(r.message, function(_i, d) {
831 frappe.ui.form.on(d, {
832 onload: function(frm) {
833 if (!frm.doc.service_level_agreement)
834 return;
835
836 frappe.call({
837 method: 'erpnext.support.doctype.service_level_agreement.service_level_agreement.get_service_level_agreement_filters',
838 args: {
839 doctype: frm.doc.doctype,
840 name: frm.doc.service_level_agreement,
841 customer: frm.doc.customer
842 },
843 callback: function (r) {
844 if (r && r.message) {
845 frm.set_query('priority', function() {
846 return {
847 filters: {
848 'name': ['in', r.message.priority],
849 }
850 };
851 });
852 frm.set_query('service_level_agreement', function() {
853 return {
854 filters: {
855 'name': ['in', r.message.service_level_agreements],
856 }
857 };
858 });
859 }
860 }
861 });
862 },
863
864 refresh: function(frm) {
865 if (frm.doc.status !== 'Closed' && frm.doc.service_level_agreement
Saqib Ansari476e81a2021-12-06 18:55:30 +0530866 && ['First Response Due', 'Resolution Due'].includes(frm.doc.agreement_status)) {
Himanshuec25d592021-06-14 19:05:52 +0530867 frappe.call({
868 'method': 'frappe.client.get',
869 args: {
870 doctype: 'Service Level Agreement',
871 name: frm.doc.service_level_agreement
872 },
873 callback: function(data) {
874 let statuses = data.message.pause_sla_on;
875 const hold_statuses = [];
876 $.each(statuses, (_i, entry) => {
877 hold_statuses.push(entry.status);
878 });
879 if (hold_statuses.includes(frm.doc.status)) {
880 frm.dashboard.clear_headline();
881 let message = {'indicator': 'orange', 'msg': __('SLA is on hold since {0}', [moment(frm.doc.on_hold_since).fromNow(true)])};
882 frm.dashboard.set_headline_alert(
883 '<div class="row">' +
884 '<div class="col-xs-12">' +
885 '<span class="indicator whitespace-nowrap '+ message.indicator +'"><span>'+ message.msg +'</span></span> ' +
886 '</div>' +
887 '</div>'
888 );
889 } else {
890 set_time_to_resolve_and_response(frm, data.message.apply_sla_for_resolution);
891 }
892 }
893 });
894 } else if (frm.doc.service_level_agreement) {
895 frm.dashboard.clear_headline();
896
897 let agreement_status = (frm.doc.agreement_status == 'Fulfilled') ?
898 {'indicator': 'green', 'msg': 'Service Level Agreement has been fulfilled'} :
899 {'indicator': 'red', 'msg': 'Service Level Agreement Failed'};
900
901 frm.dashboard.set_headline_alert(
902 '<div class="row">' +
903 '<div class="col-xs-12">' +
904 '<span class="indicator whitespace-nowrap '+ agreement_status.indicator +'"><span class="hidden-xs">'+ agreement_status.msg +'</span></span> ' +
905 '</div>' +
906 '</div>'
907 );
908 }
909 },
910 });
911 });
912 }
913 });
914});
915
916function set_time_to_resolve_and_response(frm, apply_sla_for_resolution) {
917 frm.dashboard.clear_headline();
918
Saqib24114772021-12-15 11:45:34 +0530919 let time_to_respond;
Saqib Ansari476e81a2021-12-06 18:55:30 +0530920 if (!frm.doc.first_responded_on) {
Himanshuec25d592021-06-14 19:05:52 +0530921 time_to_respond = get_time_left(frm.doc.response_by, frm.doc.agreement_status);
Saqib24114772021-12-15 11:45:34 +0530922 } else {
923 time_to_respond = get_status(frm.doc.response_by, frm.doc.first_responded_on);
Himanshuec25d592021-06-14 19:05:52 +0530924 }
925
926 let alert = `
927 <div class="row">
928 <div class="col-xs-12 col-sm-6">
929 <span class="indicator whitespace-nowrap ${time_to_respond.indicator}">
930 <span>Time to Respond: ${time_to_respond.diff_display}</span>
931 </span>
932 </div>`;
933
934
935 if (apply_sla_for_resolution) {
Saqib24114772021-12-15 11:45:34 +0530936 let time_to_resolve;
Saqib Ansari476e81a2021-12-06 18:55:30 +0530937 if (!frm.doc.resolution_date) {
Himanshuec25d592021-06-14 19:05:52 +0530938 time_to_resolve = get_time_left(frm.doc.resolution_by, frm.doc.agreement_status);
Saqib24114772021-12-15 11:45:34 +0530939 } else {
940 time_to_resolve = get_status(frm.doc.resolution_by, frm.doc.resolution_date);
Himanshuec25d592021-06-14 19:05:52 +0530941 }
942
943 alert += `
944 <div class="col-xs-12 col-sm-6">
945 <span class="indicator whitespace-nowrap ${time_to_resolve.indicator}">
946 <span>Time to Resolve: ${time_to_resolve.diff_display}</span>
947 </span>
948 </div>`;
949 }
950
951 alert += '</div>';
952
953 frm.dashboard.set_headline_alert(alert);
954}
955
956function get_time_left(timestamp, agreement_status) {
957 const diff = moment(timestamp).diff(moment());
958 const diff_display = diff >= 44500 ? moment.duration(diff).humanize() : 'Failed';
959 let indicator = (diff_display == 'Failed' && agreement_status != 'Fulfilled') ? 'red' : 'green';
960 return {'diff_display': diff_display, 'indicator': indicator};
961}
962
Saqib24114772021-12-15 11:45:34 +0530963function get_status(expected, actual) {
964 const time_left = moment(expected).diff(moment(actual));
Saqib Ansari476e81a2021-12-06 18:55:30 +0530965 if (time_left >= 0) {
Himanshuec25d592021-06-14 19:05:52 +0530966 return {'diff_display': 'Fulfilled', 'indicator': 'green'};
967 } else {
968 return {'diff_display': 'Failed', 'indicator': 'red'};
969 }
970}
971
Alanc6dc9ea2021-05-07 20:30:04 +0530972function attach_selector_button(inner_text, append_loction, context, grid_row) {
973 let $btn_div = $("<div>").css({"margin-bottom": "10px", "margin-top": "10px"})
974 .appendTo(append_loction);
975 let $btn = $(`<button class="btn btn-sm btn-default">${inner_text}</button>`)
976 .appendTo($btn_div);
977
978 $btn.on("click", function() {
979 context.show_serial_batch_selector(grid_row.frm, grid_row.doc, "", "", true);
980 });
981}