eval:doc.status=='Cancelled'
\
- on a field like \"reason_for_cancellation\" will reveal \
+ on a field like \"reason_for_cancellation\" will reveal \
\"Reason for Cancellation\" only if the record is Cancelled.\
'+__('Filter')+' | '+__('Value')+' |
---|
' + __("Click table to edit") + '
').appendTo(wrapper); + $('' + __("Click table to edit") + '
').appendTo(wrapper); var filters = JSON.parse(frm.doc.filters || '{}'); var report_filters = frappe.query_reports[frm.doc.report].filters; frm.set_value('filter_meta', JSON.stringify(report_filters)); - report_filters_list = [] + var report_filters_list = [] $.each(report_filters, function(key, val){ // Remove break fieldtype from the filters if(val.fieldtype != 'Break') { diff --git a/frappe/email/doctype/email_account/email_account.js b/frappe/email/doctype/email_account/email_account.js index 552f5108ad..cb9efd707d 100644 --- a/frappe/email/doctype/email_account/email_account.js +++ b/frappe/email/doctype/email_account/email_account.js @@ -18,7 +18,6 @@ frappe.email_defaults = { "use_imap": 1 }, "Sendgrid": { - "enable_outgoing": 0, "enable_outgoing": 1, "smtp_server": "smtp.sendgrid.net", "smtp_port": 587, @@ -71,7 +70,7 @@ frappe.ui.form.on("Email Account", { service: function(frm) { $.each(frappe.email_defaults[frm.doc.service], function(key, value) { frm.set_value(key, value); - }) + }); if (!frm.doc.use_imap) { $.each(frappe.email_defaults_pop[frm.doc.service], function(key, value) { frm.set_value(key, value); @@ -94,7 +93,7 @@ frappe.ui.form.on("Email Account", { }, enable_incoming: function(frm) { - frm.doc.no_remaining = null //perform full sync + frm.doc.no_remaining = null; //perform full sync //frm.set_df_property("append_to", "reqd", frm.doc.enable_incoming); }, @@ -114,8 +113,8 @@ frappe.ui.form.on("Email Account", { frm.events.show_gmail_message_for_less_secure_apps(frm); if(frappe.route_flags.delete_user_from_locals && frappe.route_flags.linked_user) { - delete frappe.route_flags.delete_user_from_locals - delete locals['User'][frappe.route_flags.linked_user] + delete frappe.route_flags.delete_user_from_locals; + delete locals['User'][frappe.route_flags.linked_user]; } }, @@ -134,7 +133,7 @@ frappe.ui.form.on("Email Account", { update_domain: function(frm){ if (!frm.doc.email_id && !frm.doc.service){ - return + return; } frappe.call({ @@ -145,17 +144,17 @@ frappe.ui.form.on("Email Account", { }, callback: function (r) { if (r.message) { - frm.events.set_domain_fields(frm, r.message) + frm.events.set_domain_fields(frm, r.message); } else { - frm.set_value("domain", "") + frm.set_value("domain", ""); frappe.confirm(__('Email Domain not configured for this account, Create one?'), function () { frappe.model.with_doctype("Email Domain", function() { frappe.route_options = { email_id: frm.doc.email_id }; - frappe.route_flags.return_to_email_account = 1 + frappe.route_flags.return_to_email_account = 1; var doc = frappe.model.get_new_doc("Email Domain"); frappe.set_route("Form", "Email Domain", doc.name); - }) + }); } ); } @@ -165,26 +164,26 @@ frappe.ui.form.on("Email Account", { set_domain_fields: function(frm, args) { if(!args){ - args = frappe.route_flags.set_domain_values? frappe.route_options: {} + args = frappe.route_flags.set_domain_values? frappe.route_options: {}; } - for(field in args) { + for(var field in args) { frm.set_value(field, args[field]); } - delete frappe.route_flags.set_domain_values - frappe.route_options = {} + delete frappe.route_flags.set_domain_values; + frappe.route_options = {}; }, email_sync_option: function(frm) { // confirm if the ALL sync option is selected if(frm.doc.email_sync_option == "ALL"){ - msg = __("You are selecting Sync Option as ALL, It will resync all \ + var msg = __("You are selecting Sync Option as ALL, It will resync all \ read as well as unread message from server. This may also cause the duplication\ - of Communication (emails).") + of Communication (emails)."); frappe.confirm(msg, null, function() { - frm.set_value("email_sync_option", "UNSEEN") + frm.set_value("email_sync_option", "UNSEEN"); }); } } diff --git a/frappe/email/doctype/email_alert/email_alert.js b/frappe/email/doctype/email_alert/email_alert.js index 2042b62679..f7fa09dea0 100755 --- a/frappe/email/doctype/email_alert/email_alert.js +++ b/frappe/email/doctype/email_alert/email_alert.js @@ -70,9 +70,9 @@ frappe.ui.form.on("Email Alert", { }, callback: function(r) { if(r.message) { - msgprint(r.message); + frappe.msgprint(r.message); } else { - msgprint(__('No alerts for today')); + frappe.msgprint(__('No alerts for today')); } } }); diff --git a/frappe/email/doctype/email_domain/email_domain.js b/frappe/email/doctype/email_domain/email_domain.js index 8b4fb70ffd..1716bf9900 100644 --- a/frappe/email/doctype/email_domain/email_domain.js +++ b/frappe/email/doctype/email_domain/email_domain.js @@ -9,8 +9,8 @@ frappe.ui.form.on("Email Domain", { frm.set_value("domain_name",frm.doc.email_id.split("@")[1]) } - if (frm.doc.__islocal != 1 && frappe.route_flags.return_to_email_account) { - var route = frappe.get_prev_route() + if (frm.doc.__islocal != 1 && frappe.route_flags.return_to_email_account) { + var route = frappe.get_prev_route(); delete frappe.route_flags.return_to_email_account; frappe.route_flags.set_domain_values = true diff --git a/frappe/email/doctype/email_group/email_group.js b/frappe/email/doctype/email_group/email_group.js index df4691c427..63c3832b47 100644 --- a/frappe/email/doctype/email_group/email_group.js +++ b/frappe/email/doctype/email_group/email_group.js @@ -10,7 +10,8 @@ frappe.ui.form.on("Email Group", "refresh", function(frm) { frm.add_custom_button(__("Import Subscribers"), function() { frappe.prompt({fieldtype:"Select", options: frm.doc.__onload.import_types, - label:__("Import Email From"), fieldname:"doctype", reqd:1}, function(data) { + label:__("Import Email From"), fieldname:"doctype", reqd:1}, + function(data) { frappe.call({ method: "frappe.email.doctype.email_group.email_group.import_from", args: { @@ -26,7 +27,8 @@ frappe.ui.form.on("Email Group", "refresh", function(frm) { frm.add_custom_button(__("Add Subscribers"), function() { frappe.prompt({fieldtype:"Text", - label:__("Email Addresses"), fieldname:"email_list", reqd:1}, function(data) { + label:__("Email Addresses"), fieldname:"email_list", reqd:1}, + function(data) { frappe.call({ method: "frappe.email.doctype.email_group.email_group.add_subscribers", args: { diff --git a/frappe/email/doctype/email_queue/email_queue_list.js b/frappe/email/doctype/email_queue/email_queue_list.js index d9d352f06d..0445a3ca19 100644 --- a/frappe/email/doctype/email_queue/email_queue_list.js +++ b/frappe/email/doctype/email_queue/email_queue_list.js @@ -1,10 +1,10 @@ frappe.listview_settings['Email Queue'] = { get_indicator: function(doc) { - colour = {'Sent': 'green', 'Sending': 'blue', 'Not Sent': 'grey', 'Error': 'red', 'Expired': 'orange'}; + var colour = {'Sent': 'green', 'Sending': 'blue', 'Not Sent': 'grey', 'Error': 'red', 'Expired': 'orange'}; return [__(doc.status), colour[doc.status], "status,=," + doc.status]; }, refresh: function(doclist){ - if (has_common(roles, ["Administrator", "System Manager"])){ + if (has_common(frappe.user_roles, ["Administrator", "System Manager"])){ if (cint(frappe.defaults.get_default("hold_queue"))){ doclist.page.clear_inner_toolbar() doclist.page.add_inner_button(__("Resume Sending"), function() { diff --git a/frappe/email/doctype/newsletter/newsletter.js b/frappe/email/doctype/newsletter/newsletter.js index 3f6ba4834d..48e29db048 100644 --- a/frappe/email/doctype/newsletter/newsletter.js +++ b/frappe/email/doctype/newsletter/newsletter.js @@ -1,10 +1,11 @@ // Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors // License: GNU General Public License v3. See license.txt +/* globals erpnext */ cur_frm.cscript.refresh = function(doc) { if(window.erpnext) erpnext.toggle_naming_series(); if(!doc.__islocal && !cint(doc.email_sent) && !doc.__unsaved - && inList(frappe.boot.user.can_write, doc.doctype)) { + && in_list(frappe.boot.user.can_write, doc.doctype)) { cur_frm.add_custom_button(__('Send'), function() { return $c_obj(doc, 'send_emails', '', function(r) { cur_frm.refresh(); diff --git a/frappe/printing/doctype/print_format/print_format.js b/frappe/printing/doctype/print_format/print_format.js index 216d7ff481..bd06697725 100644 --- a/frappe/printing/doctype/print_format/print_format.js +++ b/frappe/printing/doctype/print_format/print_format.js @@ -9,12 +9,12 @@ frappe.ui.form.on("Print Format", { refresh: function(frm) { frm.set_intro(""); frm.toggle_enable(["html", "doc_type", "module"], false); - if (user==="Administrator" || frm.doc.standard==="No") { + if (frappe.session.user==="Administrator" || frm.doc.standard==="No") { frm.toggle_enable(["html", "doc_type", "module"], true); frm.enable_save(); } - if(frm.doc.standard==="Yes" && user !== "Administrator") { + if(frm.doc.standard==="Yes" && frappe.session.user !== "Administrator") { frm.set_intro(__("Please duplicate this to make changes")); } frm.trigger('render_buttons'); @@ -25,7 +25,7 @@ frappe.ui.form.on("Print Format", { if(!frm.doc.custom_format) { frm.add_custom_button(__("Edit Format"), function() { if(!frm.doc.doc_type) { - msgprint(__("Please select DocType first")); + frappe.msgprint(__("Please select DocType first")); return; } frappe.set_route("print-format-builder", frm.doc.name); @@ -42,7 +42,7 @@ frappe.ui.form.on("Print Format", { } }, custom_format: function(frm) { - value = frm.doc.custom_format ? 0:1; + var value = frm.doc.custom_format ? 0:1; frm.set_value('align_labels_left', value); frm.set_value('show_section_headings', value); frm.set_value('line_breaks', value); diff --git a/frappe/printing/page/print_format_builder/print_format_builder.js b/frappe/printing/page/print_format_builder/print_format_builder.js index 4910ea42fa..8e21ee4f50 100644 --- a/frappe/printing/page/print_format_builder/print_format_builder.js +++ b/frappe/printing/page/print_format_builder/print_format_builder.js @@ -123,7 +123,7 @@ frappe.PrintFormatBuilder = Class.extend({ var doctype = me.doctype_input.get_value(), name = me.name_input.get_value(); if(!(doctype && name)) { - msgprint(__("Both DocType and Name required")); + frappe.msgprint(__("Both DocType and Name required")); return; } me.setup_new_print_format(doctype, name); @@ -272,7 +272,7 @@ frappe.PrintFormatBuilder = Class.extend({ set_column(); } else if(!in_list(["Section Break", "Column Break", "Fold"], f.fieldtype) - && f.label) { + && f.label) { if(!column) set_column(); if(f.fieldtype==="Table") { @@ -564,7 +564,7 @@ frappe.PrintFormatBuilder = Class.extend({ section.no_of_columns = 1; var $section = $(frappe.render_template("print_format_builder_section", - {section: section, me: me})) + {section: section, me: me})) .appendTo(me.page.main.find(".print-format-builder-layout")) me.setup_sortable_for_column($section.find(".print-format-builder-column").get(0)); @@ -587,8 +587,8 @@ frappe.PrintFormatBuilder = Class.extend({ var parent = $(this).parents(".print-format-builder-field:first"), doctype = parent.attr("data-doctype"), label = parent.attr("data-label"), - columns = parent.attr("data-columns").split(",") - column_names = $.map(columns, function(v) { return v.split("|")[0]; }); + columns = parent.attr("data-columns").split(","), + column_names = $.map(columns, function(v) { return v.split("|")[0]; }), widths = {}; $.each(columns, function(i, v) { @@ -622,7 +622,7 @@ frappe.PrintFormatBuilder = Class.extend({ $.each(doc_fields, function(j, f) { if (f && !in_list(column_names, f.fieldname) && !in_list(["Section Break", "Column Break"], f.fieldtype) && f.label) { - fields.push(f); + fields.push(f); } }) // render checkboxes @@ -683,26 +683,26 @@ frappe.PrintFormatBuilder = Class.extend({ get_edit_html_dialog: function(title, label, $content) { var me = this; var d = new frappe.ui.Dialog({ - title: title, - fields: [ - { - fieldname: "content", - fieldtype: "Code", - label: label - }, - { - fieldname: "help", - fieldtype: "HTML", - options: ''
- + __("You can add dynamic properties from the document by using Jinja templating.")
- + __("For example: If you want to include the document ID, use {0}", ["{{ doc.name }}
"])
- + '
'
+ + __("You can add dynamic properties from the document by using Jinja templating.")
+ + __("For example: If you want to include the document ID, use {0}", ["{{ doc.name }}
"])
+ + '
" + (value==null ? "" : $("").text(value).html()) + "" }, WorkflowState: function(value) { - workflow_state = frappe.get_doc("Workflow State", value); + var workflow_state = frappe.get_doc("Workflow State", value); if(workflow_state) { return repl(" 11) - return false; - this.visible_columns.push([df, df.colsize]); + if(df.columns) { + df.colsize=df.columns; } + else { + var colsize = 2; + switch(df.fieldtype) { + case "Text": + case "Small Text": colsize = 3; break; + case"Check": colsize = 1; + } + df.colsize = colsize; + } + + total_colsize += df.colsize; + if(total_colsize > 11) + return false; + this.visible_columns.push([df, df.colsize]); + } } // redistribute if total-col size is less than 12 @@ -586,7 +584,7 @@ frappe.ui.form.Grid = Class.extend({ // add data $.each(me.frm.doc[me.df.fieldname] || [], function(i, d) { - row = []; + var row = []; $.each(data[2], function(i, fieldname) { var value = d[fieldname]; @@ -759,9 +757,10 @@ frappe.ui.form.GridRow = Class.extend({ // index (1, 2, 3 etc) if(!this.row_index) { var txt = (this.doc ? this.doc.idx : " "); - this.row_index = $(''); } else { - me.set_field(me.field.df.parent, me.field.df.fieldname, null, - condition); + me.set_field(me.field.df.parent, me.field.df.fieldname, null, condition); } }); @@ -512,7 +511,7 @@ frappe.ui.Filter = Class.extend({ var original_docfield = me.fieldselect.fields_by_name[doctype][fieldname]; if(!original_docfield) { - msgprint(__("Field {0} is not selectable.", [fieldname])); + frappe.msgprint(__("Field {0} is not selectable.", [fieldname])); return; } @@ -784,7 +783,7 @@ frappe.ui.FieldSelect = Class.extend({ // old style if(doctype.indexOf(".")!==-1) { - parts = doctype.split("."); + var parts = doctype.split("."); doctype = parts[0]; fieldname = parts[1]; } @@ -857,14 +856,14 @@ frappe.ui.FieldSelect = Class.extend({ var label = __(df.label) + ' (' + __(df.parent) + ')'; var table = df.parent; } - if(frappe.model.no_value_type.indexOf(df.fieldtype)==-1 && + if(frappe.model.no_value_type.indexOf(df.fieldtype) == -1 && !(me.fields_by_name[df.parent] && me.fields_by_name[df.parent][df.fieldname])) { - this.options.push({ - label: label, - value: table + "." + df.fieldname, - fieldname: df.fieldname, - doctype: df.parent - }) + this.options.push({ + label: label, + value: table + "." + df.fieldname, + fieldname: df.fieldname, + doctype: df.parent + }); if(!me.fields_by_name[df.parent]) me.fields_by_name[df.parent] = {}; me.fields_by_name[df.parent][df.fieldname] = df; } diff --git a/frappe/public/js/frappe/ui/like.js b/frappe/public/js/frappe/ui/like.js index 0ebd429a2d..0dbdac72ad 100644 --- a/frappe/public/js/frappe/ui/like.js +++ b/frappe/public/js/frappe/ui/like.js @@ -3,7 +3,7 @@ frappe.ui.is_liked = function(doc) { var liked = frappe.ui.get_liked_by(doc); - return liked.indexOf(user)===-1 ? false : true; + return liked.indexOf(frappe.session.user)===-1 ? false : true; } frappe.ui.get_liked_by = function(doc) { @@ -47,10 +47,10 @@ frappe.ui.toggle_like = function($btn, doctype, name, callback) { var doc = locals[doctype] && locals[doctype][name]; if(doc) { var liked_by = JSON.parse(doc._liked_by || "[]"), - idx = liked_by.indexOf(user); + idx = liked_by.indexOf(frappe.session.user); if(add==="Yes") { if(idx===-1) - liked_by.push(user); + liked_by.push(frappe.session.user); } else { if(idx!==-1) { liked_by = liked_by.slice(0,idx).concat(liked_by.slice(idx+1)) @@ -98,7 +98,7 @@ frappe.ui.setup_like_popover = function($parent, selector) { placement: "right", content: function() { var liked_by = JSON.parse($wrapper.attr('data-liked-by') || "[]"); - + var user = frappe.session.user; // hack if ($wrapper.find(".not-liked").length) { if (liked_by.indexOf(user)!==-1) { diff --git a/frappe/public/js/frappe/ui/listing.js b/frappe/public/js/frappe/ui/listing.js index 437b16829f..39ec149ca6 100644 --- a/frappe/public/js/frappe/ui/listing.js +++ b/frappe/public/js/frappe/ui/listing.js @@ -80,7 +80,7 @@ frappe.ui.Listing = Class.extend({ return this.page.add_menu_item(label, click, icon) } else { this.wrapper.find('.list-toolbar-wrapper').removeClass("hide"); - $button = $('') + var $button = $('') .appendTo(this.wrapper.find('.list-toolbar')) .html((icon ? (" ") : "") + label) .click(click); @@ -166,7 +166,7 @@ frappe.ui.Listing = Class.extend({ }); if(frappe.model.is_submittable(this.doctype)) { this.filter_list.add_filter(this.doctype, "docstatus", "!=", 2); - }; + } }, clear: function() { @@ -246,7 +246,7 @@ frappe.ui.Listing = Class.extend({ save_list_settings_locally: function(args) { if(this.opts.save_list_settings && this.doctype && !this.docname) { // save list settings locally - list_settings = frappe.model.list_settings[this.doctype]; + var list_settings = frappe.model.list_settings[this.doctype]; if(!list_settings) { return @@ -409,7 +409,7 @@ frappe.ui.Listing = Class.extend({ }, set_filter: function(fieldname, label, no_run, no_duplicate, parent) { var filter = this.filter_list.get_filter(fieldname); - doctype = parent && this.doctype != parent? parent: this.doctype + var doctype = parent && this.doctype != parent? parent: this.doctype if(filter) { var v = cstr(filter.field.get_parsed_value()); diff --git a/frappe/public/js/frappe/ui/messages.js b/frappe/public/js/frappe/ui/messages.js index 09b6d1112b..5cd617e5d9 100644 --- a/frappe/public/js/frappe/ui/messages.js +++ b/frappe/public/js/frappe/ui/messages.js @@ -18,7 +18,7 @@ frappe.throw = function(msg) { msg = {message: msg, title: __('Error')}; } if(!msg.indicator) msg.indicator = 'red'; - msgprint(msg); + frappe.msgprint(msg); throw new Error(msg.message); } @@ -77,6 +77,7 @@ frappe.prompt = function(fields, callback, title, primary_label) { return d; } +console.warn('The globals `msgprint` and `show_alert` has been deprecated. Please use `frappe.msgprint` and `frappe.show_alert` instead.'); var msg_dialog=null; frappe.msgprint = function(msg, title) { if(!msg) return; @@ -221,8 +222,6 @@ frappe.verify_password = function(callback) { }, __("Verify Password"), __("Verify")) } -var msgprint = frappe.msgprint; - frappe.show_progress = function(title, count, total) { if(frappe.cur_progress && frappe.cur_progress.title === title && frappe.cur_progress.$wrapper.is(":visible")) { @@ -233,8 +232,8 @@ frappe.show_progress = function(title, count, total) { }); dialog.progress = $('' + - this.row_check_html + - ' ' + txt + '') + this.row_index = $( + `+ ${this.row_check_html} + ${txt}`) .appendTo(this.row) .on('click', function(e) { if(!$(e.target).hasClass('grid-row-check')) { @@ -852,7 +851,7 @@ frappe.ui.form.GridRow = Class.extend({ add_class += (["Check"].indexOf(df.fieldtype)!==-1) ? " text-center": ""; - $col = $('') + var $col = $('') .attr("data-fieldname", df.fieldname) .attr("data-fieldtype", df.fieldtype) .data("df", df) @@ -861,7 +860,7 @@ frappe.ui.form.GridRow = Class.extend({ if(frappe.ui.form.editable_row===me) { return; } - out = me.toggle_editable_row(); + var out = me.toggle_editable_row(); var col = this; setTimeout(function() { $(col).find('input[type="Text"]:first').focus(); @@ -890,7 +889,7 @@ frappe.ui.form.GridRow = Class.extend({ if(frappe.ui.form.editable_row && frappe.ui.form.editable_row !== this) { frappe.ui.form.editable_row.toggle_editable_row(false); - }; + } this.row.toggleClass('editable-row', true); @@ -942,15 +941,15 @@ frappe.ui.form.GridRow = Class.extend({ field.get_query = this.grid.get_field(df.fieldname).get_query; field.refresh(); if(field.$input) { - field.$input.addClass('input-sm'); field.$input + .addClass('input-sm') .attr('data-col-idx', column.column_index) .attr('placeholder', __(df.label)); - // flag list input - if (this.columns_list && this.columns_list.slice(-1)[0]===column) { - field.$input.attr('data-last-input', 1); - } + // flag list input + if (this.columns_list && this.columns_list.slice(-1)[0]===column) { + field.$input.attr('data-last-input', 1); + } } this.set_arrow_keys(field); @@ -964,6 +963,7 @@ frappe.ui.form.GridRow = Class.extend({ var me = this; if(field.$input) { field.$input.on('keydown', function(e) { + var { TAB, UP_ARROW, DOWN_ARROW } = frappe.ui.keyCode; if(!in_list([TAB, UP_ARROW, DOWN_ARROW], e.which)) { return; } diff --git a/frappe/public/js/frappe/form/layout.js b/frappe/public/js/frappe/form/layout.js index f81ba69e36..d44ecdaa7b 100644 --- a/frappe/public/js/frappe/form/layout.js +++ b/frappe/public/js/frappe/form/layout.js @@ -54,18 +54,14 @@ frappe.ui.form.Layout = Class.extend({ this.make_section(); } $.each(this.fields, function(i, df) { - switch(df.fieldtype) { - case "Fold": - me.make_page(df); - break; - case "Section Break": - me.make_section(df); - break; - case "Column Break": - me.make_column(df); - break; - default: - me.make_field(df); + if(df.fieldtype === "Fold") { + me.make_page(df); + } else if (df.fieldtype === "Section Break") { + me.make_section(df); + } else if (df.fieldtype === "Column Break") { + me.make_column(df); + } else { + me.make_field(df); } }); @@ -225,7 +221,7 @@ frappe.ui.form.Layout = Class.extend({ if(me.frm) { fieldobj.perm = me.frm.perm; } - }; + } refresh && fieldobj.refresh && fieldobj.refresh(); } }, @@ -249,7 +245,7 @@ frappe.ui.form.Layout = Class.extend({ }, handle_tab: function(doctype, fieldname, shift) { var me = this, - grid_row = null; + grid_row = null, prev = null, fields = me.fields_list, in_grid = false, @@ -357,7 +353,7 @@ frappe.ui.form.Layout = Class.extend({ // build dependants' dictionary var has_dep = false; - for(fkey in this.fields_list) { + for(var fkey in this.fields_list) { var f = this.fields_list[fkey]; f.dependencies_clear = true; if(f.df.depends_on) { @@ -409,7 +405,7 @@ frappe.ui.form.Layout = Class.extend({ if(expression.substr(0,5)=='eval:') { out = eval(expression.substr(5)); - } else if(expression.substr(0,3)=='fn:' && me.frm) { + } else if(expression.substr(0,3)=='fn:' && this.frm) { out = this.frm.script_manager.trigger(expression.substr(3), this.doctype, this.docname); } else { var value = doc[expression]; diff --git a/frappe/public/js/frappe/form/link_selector.js b/frappe/public/js/frappe/form/link_selector.js index be4d73d6b0..5737e132de 100644 --- a/frappe/public/js/frappe/form/link_selector.js +++ b/frappe/public/js/frappe/form/link_selector.js @@ -2,22 +2,24 @@ // MIT License. See license.txt frappe.ui.form.LinkSelector = Class.extend({ - init: function(opts) { + init: function (opts) { /* help: Options: doctype, get_query, target */ $.extend(this, opts); var me = this; - if(this.doctype!="[Select]") { - frappe.model.with_doctype(this.doctype, function(r) { + if (this.doctype != "[Select]") { + frappe.model.with_doctype(this.doctype, function (r) { me.make(); }); } else { this.make(); } }, - make: function() { + make: function () { + var me = this; + this.dialog = new frappe.ui.Dialog({ - title: __("Select {0}", [(this.doctype=='[Select]') ? __("value") : __(this.doctype)]), + title: __("Select {0}", [(this.doctype == '[Select]') ? __("value") : __(this.doctype)]), fields: [ { fieldtype: "Data", fieldname: "txt", label: __("Beginning with"), @@ -28,46 +30,45 @@ frappe.ui.form.LinkSelector = Class.extend({ } ], primary_action_label: __("Search"), - primary_action: function() { + primary_action: function () { me.search(); } }); - me = this; - if(this.txt) + if (this.txt) this.dialog.fields_dict.txt.set_input(this.txt); - this.dialog.get_input("txt").on("keypress", function(e) { - if(e.which===13) { + this.dialog.get_input("txt").on("keypress", function (e) { + if (e.which === 13) { me.search(); } }); this.dialog.show(); this.search(); }, - search: function() { + search: function () { var args = { - txt: this.dialog.fields_dict.txt.get_value(), - searchfield: "name" - }, - me = this; + txt: this.dialog.fields_dict.txt.get_value(), + searchfield: "name" + }; + var me = this; - if(this.target.set_custom_query) { + if (this.target.set_custom_query) { this.target.set_custom_query(args); } // load custom query from grid - if(this.target.is_grid && this.target.fieldinfo[this.fieldname] + if (this.target.is_grid && this.target.fieldinfo[this.fieldname] && this.target.fieldinfo[this.fieldname].get_query) { $.extend(args, - this.target.fieldinfo[this.fieldname].get_query(cur_frm.doc)); + this.target.fieldinfo[this.fieldname].get_query(cur_frm.doc)); } - frappe.link_search(this.doctype, args, function(r) { + frappe.link_search(this.doctype, args, function (r) { var parent = me.dialog.fields_dict.results.$wrapper; parent.empty(); - if(r.values.length) { - $.each(r.values, function(i, v) { + if (r.values.length) { + $.each(r.values, function (i, v) { var row = $(repl('\' + html); }, no_letterhead: !this.with_letterhead(), @@ -172,75 +175,75 @@ frappe.ui.form.PrintPreview = Class.extend({ no_heading: true }); }, - refresh_print_options: function() { + refresh_print_options: function () { this.print_formats = frappe.meta.get_print_formats(this.frm.doctype); return this.print_sel .empty().add_options(this.print_formats); }, - with_old_style: function(opts) { - frappe.require("/assets/js/print_format_v3.min.js", function() { + with_old_style: function (opts) { + frappe.require("/assets/js/print_format_v3.min.js", function () { _p.build(opts.format, opts.callback, opts.no_letterhead, opts.only_body, opts.no_heading); }); }, - print_old_style: function() { + print_old_style: function () { var me = this; - frappe.require("/assets/js/print_format_v3.min.js", function() { + frappe.require("/assets/js/print_format_v3.min.js", function () { _p.build(me.print_sel.val(), _p.go, !me.with_letterhead()); }); }, - new_page_preview_old_style: function() { + new_page_preview_old_style: function () { var me = this; - frappe.require("/assets/js/print_format_v3.min.js", function() { + frappe.require("/assets/js/print_format_v3.min.js", function () { _p.build(me.print_sel.val(), _p.preview, !me.with_letterhead()); }); }, - selected_format: function() { + selected_format: function () { return this.print_sel.val() || this.frm.meta.default_print_format || "Standard"; }, - is_old_style: function(format) { - return this.get_print_format(format).print_format_type==="Client"; + is_old_style: function (format) { + return this.get_print_format(format).print_format_type === "Client"; }, - get_print_format: function(format) { + get_print_format: function (format) { if (!format) { format = this.selected_format(); } - if(locals["Print Format"] && locals["Print Format"][format]) { + if (locals["Print Format"] && locals["Print Format"][format]) { return locals["Print Format"][format] } else { return {} } }, - with_letterhead: function() { + with_letterhead: function () { return this.print_letterhead.is(":checked") ? 1 : 0; }, - set_style: function(style) { + set_style: function (style) { frappe.dom.set_style(style || frappe.boot.print_css, "print-style"); } }); -frappe.ui.get_print_settings = function(pdf, callback, letter_head) { +frappe.ui.get_print_settings = function (pdf, callback, letter_head) { var print_settings = locals[":Print Settings"]["Print Settings"]; var default_letter_head = locals[":Company"] && frappe.defaults.get_default('company') ? locals[":Company"][frappe.defaults.get_default('company')]["default_letter_head"] : ''; - columns = [{ + var columns = [{ fieldtype: "Check", fieldname: "with_letter_head", label: __("With Letter head") - },{ + }, { fieldtype: "Select", fieldname: "letter_head", label: __("Letter Head"), depends_on: "with_letter_head", - options: $.map(frappe.boot.letter_heads, function(i,d){ return d }), + options: $.map(frappe.boot.letter_heads, function (i, d) { return d }), default: letter_head || default_letter_head }]; - if(pdf) { + if (pdf) { columns.push({ fieldtype: "Select", fieldname: "orientation", @@ -250,12 +253,12 @@ frappe.ui.get_print_settings = function(pdf, callback, letter_head) { }) } - frappe.prompt(columns, function(data) { + frappe.prompt(columns, function (data) { var data = $.extend(print_settings, data); - if(!data.with_letter_head) { + if (!data.with_letter_head) { data.letter_head = null; } - if(data.letter_head) { + if (data.letter_head) { data.letter_head = frappe.boot.letter_heads[print_settings.letter_head]; } callback(data); diff --git a/frappe/public/js/frappe/form/quick_entry.js b/frappe/public/js/frappe/form/quick_entry.js index 2e830ce54d..a267839884 100644 --- a/frappe/public/js/frappe/form/quick_entry.js +++ b/frappe/public/js/frappe/form/quick_entry.js @@ -66,7 +66,7 @@ frappe.ui.form.quick_entry = function(doctype, success) { if(data) { dialog.working = true; - values = update_doc(); + var values = update_doc(); frappe.call({ method: "frappe.client.insert", args: { diff --git a/frappe/public/js/frappe/form/save.js b/frappe/public/js/frappe/form/save.js index e75383e010..0c00ab3876 100644 --- a/frappe/public/js/frappe/form/save.js +++ b/frappe/public/js/frappe/form/save.js @@ -3,7 +3,7 @@ frappe.provide("frappe.ui.form"); -frappe.ui.form.save = function(frm, action, callback, btn) { +frappe.ui.form.save = function (frm, action, callback, btn) { $(btn).prop("disabled", true); // specified here because there are keyboard shortcuts to save @@ -17,14 +17,14 @@ frappe.ui.form.save = function(frm, action, callback, btn) { var freeze_message = working_label ? __(working_label) : ""; - var save = function() { - check_name(function() { + var save = function () { + check_name(function () { $(frm.wrapper).addClass('validated-form'); - if(check_mandatory()) { + if (check_mandatory()) { _call({ method: "frappe.desk.form.save.savedocs", - args: { doc: frm.doc, action:action}, - callback: function(r) { + args: { doc: frm.doc, action: action }, + callback: function (r) { $(document).trigger("save", [frm.doc]); callback(r); }, @@ -38,7 +38,7 @@ frappe.ui.form.save = function(frm, action, callback, btn) { }; - var cancel = function() { + var cancel = function () { var args = { doctype: frm.doc.doctype, name: frm.doc.name @@ -46,7 +46,7 @@ frappe.ui.form.save = function(frm, action, callback, btn) { // update workflow state value if workflow exists var workflow_state_fieldname = frappe.workflow.get_state_fieldname(frm.doctype); - if(workflow_state_fieldname) { + if (workflow_state_fieldname) { $.extend(args, { workflow_state_fieldname: workflow_state_fieldname, workflow_state: frm.doc[workflow_state_fieldname] @@ -57,7 +57,7 @@ frappe.ui.form.save = function(frm, action, callback, btn) { _call({ method: "frappe.desk.form.save.cancel", args: args, - callback: function(r) { + callback: function (r) { $(document).trigger("save", [frm.doc]); callback(r); }, @@ -66,17 +66,17 @@ frappe.ui.form.save = function(frm, action, callback, btn) { }); }; - var check_name = function(callback) { + var check_name = function (callback) { var doc = frm.doc; var meta = locals.DocType[doc.doctype]; - if(doc.__islocal && (meta && meta.autoname - && meta.autoname.toLowerCase()=='prompt')) { - var d = frappe.prompt(__("Name"), function(values) { + if (doc.__islocal && (meta && meta.autoname + && meta.autoname.toLowerCase() == 'prompt')) { + var d = frappe.prompt(__("Name"), function (values) { var newname = values.value; - if(newname) { + if (newname) { doc.__newname = strip(newname); } else { - msgprint(__("Name is required")); + frappe.msgprint(__("Name is required")); throw "name required"; } @@ -84,11 +84,11 @@ frappe.ui.form.save = function(frm, action, callback, btn) { }, __('Enter the name of the new {0}', [doc.doctype]), __("Create")); - if(doc.__newname) { + if (doc.__newname) { d.set_value("value", doc.__newname); } - d.onhide = function() { + d.onhide = function () { $(btn).prop("disabled", false); } } else { @@ -96,36 +96,36 @@ frappe.ui.form.save = function(frm, action, callback, btn) { } }; - var check_mandatory = function() { + var check_mandatory = function () { var me = this; var has_errors = false; frm.scroll_set = false; - if(frm.doc.docstatus==2) return true; // don't check for cancel + if (frm.doc.docstatus == 2) return true; // don't check for cancel - $.each(frappe.model.get_all_docs(frm.doc), function(i, doc) { + $.each(frappe.model.get_all_docs(frm.doc), function (i, doc) { var error_fields = []; var folded = false; - $.each(frappe.meta.docfield_list[doc.doctype] || [], function(i, docfield) { - if(docfield.fieldname) { + $.each(frappe.meta.docfield_list[doc.doctype] || [], function (i, docfield) { + if (docfield.fieldname) { var df = frappe.meta.get_docfield(doc.doctype, docfield.fieldname, frm.doc.name); - if(df.fieldtype==="Fold") { + if (df.fieldtype === "Fold") { folded = frm.layout.folded; } - if(df.reqd && !frappe.model.has_value(doc.doctype, doc.name, df.fieldname)) { + if (df.reqd && !frappe.model.has_value(doc.doctype, doc.name, df.fieldname)) { has_errors = true; error_fields[error_fields.length] = __(df.label); // scroll to field - if(!me.scroll_set) { + if (!me.scroll_set) { scroll_to(doc.parentfield || df.fieldname); } - if(folded) { + if (folded) { frm.layout.unfold(); folded = false; } @@ -133,8 +133,8 @@ frappe.ui.form.save = function(frm, action, callback, btn) { } }); - if(error_fields.length) { - if(doc.parenttype) { + if (error_fields.length) { + if (doc.parenttype) { var message = __('Mandatory fields required in table {0}, Row {1}', [__(frappe.meta.docfield_map[doc.parenttype][doc.parentfield].label).bold(), doc.idx]); } else { @@ -142,7 +142,7 @@ frappe.ui.form.save = function(frm, action, callback, btn) { } message = message + '\ %(name)s\ @@ -80,56 +81,58 @@ frappe.ui.form.LinkSelector = Class.extend({ row.find("a") .attr('data-value', v[0]) - .click(function() { - var value = $(this).attr("data-value"); - var $link = this; - if(me.target.is_grid) { - // set in grid - me.set_in_grid(value); - } else { - if(me.target.doctype) - me.target.parse_validate_and_set_in_model(value); - else { - me.target.set_input(value); - me.target.$input.trigger("change"); + .click(function () { + var value = $(this).attr("data-value"); + var $link = this; + if (me.target.is_grid) { + // set in grid + me.set_in_grid(value); + } else { + if (me.target.doctype) + me.target.parse_validate_and_set_in_model(value); + else { + me.target.set_input(value); + me.target.$input.trigger("change"); + } + me.dialog.hide(); } - me.dialog.hide(); - } - return false; - }) + return false; + }) }) } else { $('').appendTo(parent).find(".new-doc").click(function() { + + __("Make a new {0}", [__(me.doctype)]) + "") : '') + + '').appendTo(parent).find(".new-doc").click(function () { me.target.new_doc(); }); } }, this.dialog.get_primary_btn()); }, - set_in_grid: function(value) { + set_in_grid: function (value) { var me = this, updated = false; - if(this.qty_fieldname) { - frappe.prompt({fieldname:"qty", fieldtype:"Float", label:"Qty", - "default": 1, reqd: 1}, function(data) { - $.each(me.target.frm.doc[me.target.df.fieldname] || [], function(i, d) { - if(d[me.fieldname]===value) { + if (this.qty_fieldname) { + frappe.prompt({ + fieldname: "qty", fieldtype: "Float", label: "Qty", + "default": 1, reqd: 1 + }, function (data) { + $.each(me.target.frm.doc[me.target.df.fieldname] || [], function (i, d) { + if (d[me.fieldname] === value) { frappe.model.set_value(d.doctype, d.name, me.qty_fieldname, data.qty); - show_alert(__("Added {0} ({1})", [value, d[me.qty_fieldname]])); + frappe.show_alert(__("Added {0} ({1})", [value, d[me.qty_fieldname]])); updated = true; return false; } }); - if(!updated) { + if (!updated) { var d = me.target.add_new_row(); frappe.model.set_value(d.doctype, d.name, me.fieldname, value); - frappe.after_ajax(function() { - setTimeout(function() { + frappe.after_ajax(function () { + setTimeout(function () { frappe.model.set_value(d.doctype, d.name, me.qty_fieldname, data.qty); - show_alert(__("Added {0} ({1})", [value, data.qty])); + frappe.show_alert(__("Added {0} ({1})", [value, data.qty])); }, 100); }); } @@ -137,19 +140,19 @@ frappe.ui.form.LinkSelector = Class.extend({ } else { var d = me.target.add_new_row(); frappe.model.set_value(d.doctype, d.name, me.fieldname, value); - show_alert(__("{0} added", [value])); + frappe.show_alert(__("{0} added", [value])); } } }); -frappe.link_search = function(doctype, args, callback, btn) { - if(!args) { +frappe.link_search = function (doctype, args, callback, btn) { + if (!args) { args = { txt: '' } } args.doctype = doctype; - if(!args.searchfield) { + if (!args.searchfield) { args.searchfield = 'name'; } @@ -157,7 +160,7 @@ frappe.link_search = function(doctype, args, callback, btn) { method: "frappe.desk.search.search_widget", type: "GET", args: args, - callback: function(r) { + callback: function (r) { callback && callback(r); }, btn: btn diff --git a/frappe/public/js/frappe/form/print.js b/frappe/public/js/frappe/form/print.js index 555c85c9d9..18a5891f36 100644 --- a/frappe/public/js/frappe/form/print.js +++ b/frappe/public/js/frappe/form/print.js @@ -1,26 +1,26 @@ frappe.provide("frappe.ui.form"); frappe.ui.form.PrintPreview = Class.extend({ - init: function(opts) { + init: function (opts) { $.extend(this, opts); this.make(); this.bind_events(); }, - make: function() { + make: function () { this.wrapper = this.frm.page.add_view("print", frappe.render_template("print_layout", {})); // only system manager can edit this.wrapper.find(".btn-print-edit").toggle(frappe.user.has_role("System Manager")); }, - bind_events: function() { + bind_events: function () { var me = this; - this.wrapper.find(".btn-print-close").click(function() { + this.wrapper.find(".btn-print-close").click(function () { me.frm.hide_print(); }); // hide print view on pressing escape, only if there is no focus on any input - $(document).on("keydown", function(e) { - if (e.which===27 && me.frm && e.target===document.body) { + $(document).on("keydown", function (e) { + if (e.which === 27 && me.frm && e.target === document.body) { me.frm.hide_print(); } }); @@ -28,78 +28,81 @@ frappe.ui.form.PrintPreview = Class.extend({ this.print_formats = frappe.meta.get_print_formats(this.frm.meta.name); this.print_letterhead = this.wrapper .find(".print-letterhead") - .on("change", function() { me.print_sel.trigger("change"); }) + .on("change", function () { me.print_sel.trigger("change"); }) .prop("checked", cint( (frappe.model.get_doc(":Print Settings", "Print Settings") - || {with_letterhead: 1}).with_letterhead) ? true : false); + || { with_letterhead: 1 }).with_letterhead) ? true : false); this.print_sel = this.wrapper .find(".print-preview-select") - .on("change", function() { + .on("change", function () { me.multilingual_preview() }); //On selection of language get code and pass it to preview method this.language_sel = this.wrapper .find(".languages") - .on("change", function(){ + .on("change", function () { me.lang_code = me.language_sel.val() me.multilingual_preview() }); - this.wrapper.find(".btn-print-print").click(function() { - if(me.is_old_style()) { + this.wrapper.find(".btn-print-print").click(function () { + if (me.is_old_style()) { me.print_old_style(); } else { me.printit(); } }); - this.wrapper.find(".btn-print-preview").click(function() { - if(me.is_old_style()) { + this.wrapper.find(".btn-print-preview").click(function () { + if (me.is_old_style()) { me.new_page_preview_old_style(); } else { me.new_page_preview(); } }); - this.wrapper.find(".btn-download-pdf").click(function() { - if(!me.is_old_style()) { + this.wrapper.find(".btn-download-pdf").click(function () { + if (!me.is_old_style()) { var w = window.open( frappe.urllib.get_full_url("/api/method/frappe.utils.print_format.download_pdf?" - +"doctype="+encodeURIComponent(me.frm.doc.doctype) - +"&name="+encodeURIComponent(me.frm.doc.name) - +"&format="+me.selected_format() - +"&no_letterhead="+(me.with_letterhead() ? "0" : "1") - +(me.lang_code ? ("&_lang="+me.lang_code) : ""))); - if(!w) { - msgprint(__("Please enable pop-ups")); return; + + "doctype=" + encodeURIComponent(me.frm.doc.doctype) + + "&name=" + encodeURIComponent(me.frm.doc.name) + + "&format=" + me.selected_format() + + "&no_letterhead=" + (me.with_letterhead() ? "0" : "1") + + (me.lang_code ? ("&_lang=" + me.lang_code) : "")) + ); + if (!w) { + frappe.msgprint(__("Please enable pop-ups")); return; } } }); - this.wrapper.find(".btn-print-edit").on("click", function() { + this.wrapper.find(".btn-print-edit").on("click", function () { var print_format = me.get_print_format(); - if(print_format && print_format.name) { - if(print_format.print_format_builder) { + if (print_format && print_format.name) { + if (print_format.print_format_builder) { frappe.set_route("print-format-builder", print_format.name); } else { frappe.set_route("Form", "Print Format", print_format.name); } } else { // start a new print format - frappe.prompt({fieldname:"print_format_name", fieldtype:"Data", reqd: 1, - label:"New Print Format Name"}, function(data) { - frappe.route_options = { - make_new: true, - doctype: me.frm.doctype, - name: data.print_format_name - }; - frappe.set_route("print-format-builder"); + frappe.prompt({ + fieldname: "print_format_name", fieldtype: "Data", reqd: 1, + label: "New Print Format Name" + }, function (data) { + frappe.route_options = { + make_new: true, + doctype: me.frm.doctype, + name: data.print_format_name + }; + frappe.set_route("print-format-builder"); }, __("New Custom Print Format"), __("Start")); } }); }, - set_user_lang: function(){ + set_user_lang: function () { this.lang_code = this.frm.doc.language; // Load all languages in the field this.language_sel.empty() @@ -107,9 +110,9 @@ frappe.ui.form.PrintPreview = Class.extend({ .val(this.lang_code); this.preview(); }, - multilingual_preview: function(){ + multilingual_preview: function () { var me = this; - if(this.is_old_style()) { + if (this.is_old_style()) { me.wrapper.find(".btn-download-pdf").toggle(false); me.set_style(); me.preview_old_style(); @@ -118,30 +121,30 @@ frappe.ui.form.PrintPreview = Class.extend({ me.preview(); } }, - preview: function() { + preview: function () { var me = this; - this.get_print_html(function(out) { + this.get_print_html(function (out) { me.wrapper.find(".print-format").html(out.html); me.set_style(out.style); }); }, - printit: function() { + printit: function () { this.new_page_preview(true); }, - new_page_preview: function(printit) { + new_page_preview: function (printit) { var me = this; var w = window.open(frappe.urllib.get_full_url("/printview?" - +"doctype="+encodeURIComponent(me.frm.doc.doctype) - +"&name="+encodeURIComponent(me.frm.doc.name) - +(printit ? "&trigger_print=1" : "") - +"&format="+me.selected_format() - +"&no_letterhead="+(me.with_letterhead() ? "0" : "1") - +(me.lang_code ? ("&_lang="+me.lang_code) : ""))); - if(!w) { - msgprint(__("Please enable pop-ups")); return; + + "doctype=" + encodeURIComponent(me.frm.doc.doctype) + + "&name=" + encodeURIComponent(me.frm.doc.name) + + (printit ? "&trigger_print=1" : "") + + "&format=" + me.selected_format() + + "&no_letterhead=" + (me.with_letterhead() ? "0" : "1") + + (me.lang_code ? ("&_lang=" + me.lang_code) : ""))); + if (!w) { + frappe.msgprint(__("Please enable pop-ups")); return; } }, - get_print_html: function(callback) { + get_print_html: function (callback) { frappe.call({ method: "frappe.www.printview.get_html_and_style", args: { @@ -150,21 +153,21 @@ frappe.ui.form.PrintPreview = Class.extend({ no_letterhead: !this.with_letterhead() ? 1 : 0, _lang: this.lang_code }, - callback: function(r) { - if(!r.exc) { + callback: function (r) { + if (!r.exc) { callback(r.message); } } }); }, - preview_old_style: function() { + preview_old_style: function () { var me = this; this.with_old_style({ format: me.print_sel.val(), - callback: function(html) { + callback: function (html) { me.wrapper.find(".print-format").html('
' + __("No Results") + '' + (frappe.model.can_create(me.doctype) ? ('
' - + __("Make a new {0}", [__(me.doctype)]) + "") : '') - + '' - +__("Warning: This Print Format is in old style and cannot be generated via the API.") - +'' + + __("Warning: This Print Format is in old style and cannot be generated via the API.") + + '"; - msgprint({ + frappe.msgprint({ message: message, indicator: 'red', title: __('Missing Fields') @@ -153,15 +153,15 @@ frappe.ui.form.save = function(frm, action, callback, btn) { return !has_errors; }; - var scroll_to = function(fieldname) { + var scroll_to = function (fieldname) { var f = cur_frm.fields_dict[fieldname]; - if(f) { + if (f) { $(document).scrollTop($(f.wrapper).offset().top - 60); } frm.scroll_set = true; }; - var _call = function(opts) { + var _call = function (opts) { // opts = { // method: "some server method", // args: {args to be passed}, @@ -170,7 +170,7 @@ frappe.ui.form.save = function(frm, action, callback, btn) { // } $(opts.btn).prop("disabled", true); - if(frappe.ui.form.is_saving) { + if (frappe.ui.form.is_saving) { // this is likely to happen if the user presses the shortcut cmd+s for a longer duration or uses double click // no need to show this to user, as they can see "Saving" in freeze message console.log("Already saving. Please wait a few moments.") @@ -184,49 +184,50 @@ frappe.ui.form.save = function(frm, action, callback, btn) { method: opts.method, args: opts.args, btn: opts.btn, - callback: function(r) { + callback: function (r) { opts.callback && opts.callback(r); }, - always: function(r) { + always: function (r) { frappe.ui.form.is_saving = false; - if(r) { + if (r) { var doc = r.docs && r.docs[0]; - if(doc) { + if (doc) { frappe.ui.form.update_calling_link(doc); - } + } } } }) }; - if(action==="cancel") { + if (action === "cancel") { cancel(); } else { save(); } } -frappe.ui.form.update_calling_link = function(newdoc) { - if(frappe._from_link && newdoc.doctype===frappe._from_link.df.options) { +frappe.ui.form.update_calling_link = function (newdoc) { + if (frappe._from_link && newdoc.doctype === frappe._from_link.df.options) { var doc = frappe.get_doc(frappe._from_link.doctype, frappe._from_link.docname); // set value - if (doc && doc.parentfield){ + if (doc && doc.parentfield) { //update values for child table - $.each(frappe._from_link.frm.fields_dict[doc.parentfield].grid.grid_rows, function(index, field) { - if(field.doc && field.doc.name===frappe._from_link.docname){ + $.each(frappe._from_link.frm.fields_dict[doc.parentfield].grid.grid_rows, function (index, field) { + if (field.doc && field.doc.name === frappe._from_link.docname) { frappe._from_link.set_value(newdoc.name); - }}); + } + }); } else { frappe._from_link.set_value(newdoc.name); - } + } // refresh field frappe._from_link.refresh(); // if from form, switch - if(frappe._from_link.frm) { + if (frappe._from_link.frm) { frappe.set_route("Form", frappe._from_link.frm.doctype, frappe._from_link.frm.docname); - setTimeout(function() { frappe.utils.scroll_to(frappe._from_link_scrollY); }, 100); + setTimeout(function () { frappe.utils.scroll_to(frappe._from_link_scrollY); }, 100); } frappe._from_link = null; diff --git a/frappe/public/js/frappe/form/script_manager.js b/frappe/public/js/frappe/form/script_manager.js index 146ec25a8e..1591f0a3bb 100644 --- a/frappe/public/js/frappe/form/script_manager.js +++ b/frappe/public/js/frappe/form/script_manager.js @@ -70,7 +70,7 @@ frappe.ui.form.ScriptManager = Class.extend({ var me = this; doctype = doctype || this.frm.doctype; name = name || this.frm.docname; - handlers = this.get_handlers(event_name, doctype, name, callback); + var handlers = this.get_handlers(event_name, doctype, name, callback); if(callback) handlers.push(callback); return $.when.apply($, $.map(handlers, function(fn) { return fn(); })); @@ -114,8 +114,8 @@ frappe.ui.form.ScriptManager = Class.extend({ } function setup_add_fetch(df) { - if((in_list(['Data', 'Read Only', 'Text', 'Small Text', - 'Text Editor', 'Code'], df.fieldtype) || df.read_only==1) + if((['Data', 'Read Only', 'Text', 'Small Text', + 'Text Editor', 'Code'].includes(df.fieldtype) || df.read_only==1) && df.options && df.options.indexOf(".")!=-1) { var parts = df.options.split("."); me.frm.add_fetch(parts[0], parts[1], df.fieldname); @@ -138,7 +138,7 @@ frappe.ui.form.ScriptManager = Class.extend({ this.trigger('setup'); }, log_error: function(caller, e) { - show_alert("Error in Client Script."); + frappe.show_alert("Error in Client Script."); console.group && console.group(); console.log("----- error in client script -----"); console.log("method: " + caller); diff --git a/frappe/public/js/frappe/form/share.js b/frappe/public/js/frappe/form/share.js index 41f811953f..828ea69ede 100644 --- a/frappe/public/js/frappe/form/share.js +++ b/frappe/public/js/frappe/form/share.js @@ -117,7 +117,7 @@ frappe.ui.form.Share = Class.extend({ options: "User", filters: { "user_type": "System User", - "name": ["!=", user] + "name": ["!=", frappe.session.user] } }, only_input: true, @@ -163,7 +163,7 @@ frappe.ui.form.Share = Class.extend({ $(d.body).find(".edit-share").on("click", function() { var user = $(this).parents(".shared-user:first").attr("data-user") || "", value = $(this).prop("checked") ? 1 : 0, - property = $(this).attr("name") + property = $(this).attr("name"), everyone = cint($(this).parents(".shared-user:first").attr("data-everyone")); frappe.call({ diff --git a/frappe/public/js/frappe/form/sidebar.js b/frappe/public/js/frappe/form/sidebar.js index 080e6cd898..6da3c6f8d8 100644 --- a/frappe/public/js/frappe/form/sidebar.js +++ b/frappe/public/js/frappe/form/sidebar.js @@ -58,10 +58,10 @@ frappe.ui.form.Sidebar = Class.extend({ this.frm.tags && this.frm.tags.refresh(this.frm.doc._user_tags); this.sidebar.find(".modified-by").html(__("{0} edited this {1}", ["" + frappe.user.full_name(this.frm.doc.modified_by) + "", - "
- ' + error_fields.join('
- ') + "
" + comment_when(this.frm.doc.modified)])); + "
" + comment_when(this.frm.doc.modified)])); this.sidebar.find(".created-by").html(__("{0} created this {1}", ["" + frappe.user.full_name(this.frm.doc.owner) + "", - "
" + comment_when(this.frm.doc.creation)])); + "
" + comment_when(this.frm.doc.creation)])); this.refresh_like(); this.setup_ratings(); @@ -151,11 +151,11 @@ frappe.ui.form.Sidebar = Class.extend({ }, setup_ratings: function() { - _ratings = this.frm.get_docinfo().rating || 0; + var _ratings = this.frm.get_docinfo().rating || 0; if(_ratings) { this.ratings.removeClass("hide"); - rating_icons = frappe.render_template("rating_icons", {rating: _ratings, show_label: false}); + var rating_icons = frappe.render_template("rating_icons", {rating: _ratings, show_label: false}); this.ratings.find(".rating-icons").html(rating_icons); } } diff --git a/frappe/public/js/frappe/form/toolbar.js b/frappe/public/js/frappe/form/toolbar.js index 80ee2d7341..aa0a822c0b 100644 --- a/frappe/public/js/frappe/form/toolbar.js +++ b/frappe/public/js/frappe/form/toolbar.js @@ -114,7 +114,7 @@ frappe.ui.form.Toolbar = Class.extend({ // Print if(!is_submittable || docstatus == 1 || (allow_print_for_cancelled && docstatus == 2)|| - (allow_print_for_draft && docstatus == 0)) { + (allow_print_for_draft && docstatus == 0)) { if(frappe.model.can_print(null, me.frm)) { this.page.add_menu_item(__("Print"), function() { me.frm.print_doc();}, true); @@ -159,7 +159,7 @@ frappe.ui.form.Toolbar = Class.extend({ me.frm.savetrash();}, true); } - if(in_list(roles, "System Manager")) { + if(frappe.user_roles.includes("System Manager")) { this.page.add_menu_item(__("Customize"), function() { frappe.set_route("Form", "Customize Form", { doc_type: me.frm.doctype @@ -178,7 +178,7 @@ frappe.ui.form.Toolbar = Class.extend({ if(!this.frm.doc.__unsaved) { if(is_submittable && docstatus == 1) { this.page.add_menu_item(__("Request Feedback"), function() { - feedback = new frappe.utils.Feedback(); + var feedback = new frappe.utils.Feedback(); feedback.manual_feedback_request(me.frm.doc); }, true) } diff --git a/frappe/public/js/frappe/form/workflow.js b/frappe/public/js/frappe/form/workflow.js index 69bc1092d6..e3fde7ae84 100644 --- a/frappe/public/js/frappe/form/workflow.js +++ b/frappe/public/js/frappe/form/workflow.js @@ -73,7 +73,7 @@ frappe.ui.form.States = Class.extend({ } $.each(frappe.workflow.get_transitions(this.frm.doctype, state), function(i, d) { - if(in_list(roles, d.allowed)) { + if(frappe.user_roles.includes(d.allowed)) { added = true; me.frm.page.add_action_item(__(d.action), function() { var action = d.action; @@ -112,10 +112,10 @@ frappe.ui.form.States = Class.extend({ } else if(new_docstatus==2 && me.frm.doc.docstatus==1) { me.frm.savecancel(null, success, on_error); } else { - msgprint(__("Document Status transition from ") + me.frm.doc.docstatus + " " + frappe.msgprint(__("Document Status transition from ") + me.frm.doc.docstatus + " " + __("to") + new_docstatus + " " + __("is not allowed.")); - msgprint(__("Document Status transition from {0} to {1} is not allowed", [me.frm.doc.docstatus, new_docstatus])); + frappe.msgprint(__("Document Status transition from {0} to {1} is not allowed", [me.frm.doc.docstatus, new_docstatus])); return false; } diff --git a/frappe/public/js/frappe/list/list_renderer.js b/frappe/public/js/frappe/list/list_renderer.js index 1f0209f74b..4fa52171e1 100644 --- a/frappe/public/js/frappe/list/list_renderer.js +++ b/frappe/public/js/frappe/list/list_renderer.js @@ -108,8 +108,8 @@ frappe.views.ListRenderer = Class.extend({ } // enabled / disabled - if (frappe.meta.has_field(this.doctype, 'enabled')) { add_field('enabled'); }; - if (frappe.meta.has_field(this.doctype, 'disabled')) { add_field('disabled'); }; + if (frappe.meta.has_field(this.doctype, 'enabled')) { add_field('enabled'); } + if (frappe.meta.has_field(this.doctype, 'disabled')) { add_field('disabled'); } // add workflow field (as priority) this.workflow_state_fieldname = frappe.workflow.get_state_fieldname(this.doctype); @@ -133,7 +133,7 @@ frappe.views.ListRenderer = Class.extend({ add_field(df.options.split(':')[1]); } else { add_field(df.options); - }; + } } } }); @@ -424,7 +424,7 @@ frappe.views.ListRenderer = Class.extend({ this.prepare_when(data, data.modified); // nulls as strings - for (key in data) { + for (var key in data) { if (data[key] == null) { data[key] = ''; } @@ -485,8 +485,8 @@ frappe.views.ListRenderer = Class.extend({ prepare_when: function (data, date_str) { if (!date_str) date_str = data.modified; // when - data.when = (dateutil.str_to_user(date_str)).split(' ')[0]; - var diff = dateutil.get_diff(dateutil.get_today(), date_str.split(' ')[0]); + data.when = (frappe.datetime.str_to_user(date_str)).split(' ')[0]; + var diff = frappe.datetime.get_diff(frappe.datetime.get_today(), date_str.split(' ')[0]); if (diff === 0) { data.when = comment_when(date_str); } diff --git a/frappe/public/js/frappe/list/list_sidebar.js b/frappe/public/js/frappe/list/list_sidebar.js index 58ce23209d..375bd0d6c4 100644 --- a/frappe/public/js/frappe/list/list_sidebar.js +++ b/frappe/public/js/frappe/list/list_sidebar.js @@ -212,7 +212,7 @@ frappe.views.ListSidebar = Class.extend({ .then(function() { d.hide(); }, function(err) { - msgprint(err); + frappe.msgprint(err); }); } }); @@ -273,15 +273,15 @@ frappe.views.ListSidebar = Class.extend({ var $dropdown = this.page.sidebar.find('.email-account-dropdown'); var divider = false; - if(has_common(roles, ["System Manager", "Administrator"])) { + if(has_common(frappe.user_roles, ["System Manager", "Administrator"])) { $(''+ __("New Email Account") +' ') .appendTo($dropdown) } - accounts = frappe.boot.email_accounts; + var accounts = frappe.boot.email_accounts; accounts.forEach(function(account) { - email_account = (account.email_id == "All Accounts")? "All Accounts": account.email_account; + var email_account = (account.email_id == "All Accounts")? "All Accounts": account.email_account; var route = ["List", "Communication", "Inbox", email_account].join('/'); if(!divider) { $('').appendTo($dropdown); @@ -318,9 +318,9 @@ frappe.views.ListSidebar = Class.extend({ me.defined_category = r.message; if (r.message.defined_cat ){ me.defined_category = r.message.defined_cat - me.cats = {}; + me.cats = {}; //structure the tag categories - for (i in me.defined_category){ + for (var i in me.defined_category){ if (me.cats[me.defined_category[i].category]===undefined){ me.cats[me.defined_category[i].category]=[me.defined_category[i].tag]; }else{ diff --git a/frappe/public/js/frappe/list/list_view.js b/frappe/public/js/frappe/list/list_view.js index e673a297c4..af811faa4b 100644 --- a/frappe/public/js/frappe/list/list_view.js +++ b/frappe/public/js/frappe/list/list_view.js @@ -302,7 +302,7 @@ frappe.views.ListView = frappe.ui.BaseList.extend({ set_filters: function (filters) { var me = this; $.each(filters, function (i, f) { - hidden = false + var hidden = false if (f.length === 3) { f = [me.doctype, f[0], f[1], f[2]] } else if (f.length === 5) { @@ -377,7 +377,7 @@ frappe.views.ListView = frappe.ui.BaseList.extend({ if (this.list_renderer.settings.list_view_doc) { this.list_renderer.settings.list_view_doc(this); } else { - doctype = this.list_renderer.no_result_doctype? this.list_renderer.no_result_doctype: this.doctype + var doctype = this.list_renderer.no_result_doctype? this.list_renderer.no_result_doctype: this.doctype $(this.wrapper).on('click', `button[list_view_doc='${doctype}']`, function () { if (me.list_renderer.make_new_doc) me.list_renderer.make_new_doc() @@ -563,18 +563,18 @@ frappe.views.ListView = frappe.ui.BaseList.extend({ return order_by; }, assigned_to_me: function () { - this.filter_list.add_filter(this.doctype, '_assign', 'like', '%' + user + '%'); + this.filter_list.add_filter(this.doctype, '_assign', 'like', '%' + frappe.session.user + '%'); this.run(); }, liked_by_me: function () { - this.filter_list.add_filter(this.doctype, '_liked_by', 'like', '%' + user + '%'); + this.filter_list.add_filter(this.doctype, '_liked_by', 'like', '%' + frappe.session.user + '%'); this.run(); }, remove_liked_by_me: function () { this.filter_list.get_filter('_liked_by').remove(); }, is_star_filtered: function () { - return this.filter_list.filter_exists(this.doctype, '_liked_by', 'like', '%' + user + '%'); + return this.filter_list.filter_exists(this.doctype, '_liked_by', 'like', '%' + frappe.session.user + '%'); }, init_menu: function () { var me = this; @@ -606,7 +606,7 @@ frappe.views.ListView = frappe.ui.BaseList.extend({ }); }, true); } - if (roles.includes('System Manager')) { + if (frappe.user_roles.includes('System Manager')) { this.page.add_menu_item(__('Role Permissions Manager'), function () { frappe.set_route('permission-manager', { doctype: me.doctype @@ -627,7 +627,7 @@ frappe.views.ListView = frappe.ui.BaseList.extend({ frappe.add_to_desktop(me.doctype, me.doctype); }, true); - if (roles.includes('System Manager') && frappe.boot.developer_mode === 1) { + if (frappe.user_roles.includes('System Manager') && frappe.boot.developer_mode === 1) { // edit doctype this.page.add_menu_item(__('Edit DocType'), function () { frappe.set_route('Form', 'DocType', me.doctype); @@ -683,7 +683,7 @@ frappe.views.ListView = frappe.ui.BaseList.extend({ return !is_submittable || doc.docstatus === 1 || (allow_print_for_cancelled && doc.docstatus == 2) || (allow_print_for_draft && doc.docstatus == 0) || - roles.includes('Administrator') + frappe.user_roles.includes('Administrator') }).map(function (doc) { return doc.name }); @@ -708,11 +708,11 @@ frappe.views.ListView = frappe.ui.BaseList.extend({ }); dialog.set_primary_action(__('Print'), function () { - args = dialog.get_values(); + var args = dialog.get_values(); if (!args) return; var default_print_format = locals.DocType[me.doctype].default_print_format; - with_letterhead = args.with_letterhead ? 1 : 0; - print_format = args.print_sel ? args.print_sel : default_print_format; + var with_letterhead = args.with_letterhead ? 1 : 0; + var print_format = args.print_sel ? args.print_sel : default_print_format; var json_string = JSON.stringify(valid_docs); var w = window.open('/api/method/frappe.utils.print_format.download_multi_pdf?' @@ -725,7 +725,7 @@ frappe.views.ListView = frappe.ui.BaseList.extend({ } }); - print_formats = frappe.meta.get_print_formats(me.doctype); + var print_formats = frappe.meta.get_print_formats(me.doctype); dialog.fields_dict.print_sel.$input.empty().add_options(print_formats); dialog.show(); diff --git a/frappe/public/js/frappe/misc/common.js b/frappe/public/js/frappe/misc/common.js index 808ae094de..eab3f8e6b2 100644 --- a/frappe/public/js/frappe/misc/common.js +++ b/frappe/public/js/frappe/misc/common.js @@ -30,7 +30,7 @@ frappe.avatar = function(user, css_class, title) { return repl('\ ', { + title="%(title)s">', { image: image, title: title, abbr: user_info.abbr, @@ -93,7 +93,7 @@ frappe.get_gravatar = function(email_id) { function repl(s, dict) { if(s==null)return ''; - for(key in dict) { + for(var key in dict) { s = s.split("%("+key+")s").join(dict[key]); } return s; @@ -162,8 +162,8 @@ function getCookies() { c.match(/(?:^|\s+)([!#$%&'*+\-.0-9A-Z^`a-z|~]+)=([!#$%&'*+\-.0-9A-Z^`a-z|~]*|"(?:[\x20-\x7E\x80\xFF]|\\[\x00-\x7F])*")(?=\s*[,;]|$)/g).map(function($0, $1) { var name = $0, value = $1.charAt(0) === '"' - ? $1.substr(1, -1).replace(/\\(.)/g, "$1") - : $1; + ? $1.substr(1, -1).replace(/\\(.)/g, "$1") + : $1; cookies[name] = value; }); } diff --git a/frappe/public/js/frappe/misc/datetime.js b/frappe/public/js/frappe/misc/datetime.js index 53a9c022bd..e8cd44862f 100644 --- a/frappe/public/js/frappe/misc/datetime.js +++ b/frappe/public/js/frappe/misc/datetime.js @@ -10,8 +10,8 @@ frappe.provide("frappe.datetime"); $.extend(frappe.datetime, { convert_to_user_tz: function(date, format) { // format defaults to true - if(sys_defaults.time_zone) { - var date_obj = moment.tz(date, sys_defaults.time_zone).local(); + if(frappe.sys_defaults.time_zone) { + var date_obj = moment.tz(date, frappe.sys_defaults.time_zone).local(); } else { var date_obj = moment(date); } @@ -22,8 +22,8 @@ $.extend(frappe.datetime, { convert_to_system_tz: function(date, format) { // format defaults to true - if(sys_defaults.time_zone) { - var date_obj = moment(date).tz(sys_defaults.time_zone); + if(frappe.sys_defaults.time_zone) { + var date_obj = moment(date).tz(frappe.sys_defaults.time_zone); } else { var date_obj = moment(date); } @@ -32,8 +32,8 @@ $.extend(frappe.datetime, { }, is_timezone_same: function() { - if(sys_defaults.time_zone) { - return moment().tz(sys_defaults.time_zone).utcOffset() === moment().utcOffset(); + if(frappe.sys_defaults.time_zone) { + return moment().tz(frappe.sys_defaults.time_zone).utcOffset() === moment().utcOffset(); } else { return true; } @@ -48,7 +48,7 @@ $.extend(frappe.datetime, { }, obj_to_user: function(d) { - return moment(d).format(dateutil.get_user_fmt().toUpperCase()); + return moment(d).format(frappe.datetime.get_user_fmt().toUpperCase()); }, get_diff: function(d1, d2) { @@ -88,12 +88,12 @@ $.extend(frappe.datetime, { }, get_user_fmt: function() { - return sys_defaults.date_format || "yyyy-mm-dd"; + return frappe.sys_defaults.date_format || "yyyy-mm-dd"; }, str_to_user: function(val, no_time_str) { if(!val) return ""; - var user_fmt = dateutil.get_user_fmt().toUpperCase(); + var user_fmt = frappe.datetime.get_user_fmt().toUpperCase(); if(typeof val !== "string" || val.indexOf(" ")===-1) { return moment(val).format(user_fmt); } else { @@ -110,7 +110,7 @@ $.extend(frappe.datetime, { }, user_to_str: function(val, no_time_str) { - var user_fmt = dateutil.get_user_fmt().toUpperCase(); + var user_fmt = frappe.datetime.get_user_fmt().toUpperCase(); var system_fmt = "YYYY-MM-DD"; if(val.indexOf(" ")!==-1) { @@ -124,7 +124,7 @@ $.extend(frappe.datetime, { }, user_to_obj: function(d) { - return dateutil.str_to_obj(dateutil.user_to_str(d)); + return frappe.datetime.str_to_obj(frappe.datetime.user_to_str(d)); }, global_date_format: function(d) { @@ -155,6 +155,4 @@ $.extend(frappe.datetime, { }); -// globals (deprecate) -var date = dateutil = frappe.datetime; -var get_today = frappe.datetime.get_today; +console.warn('The globals `dateutil` and `get_today` are deprecated. Please use `frappe.datetime` instead.') diff --git a/frappe/public/js/frappe/misc/number_format.js b/frappe/public/js/frappe/misc/number_format.js index fa77b3bbfc..c9b465da80 100644 --- a/frappe/public/js/frappe/misc/number_format.js +++ b/frappe/public/js/frappe/misc/number_format.js @@ -1,55 +1,55 @@ // Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors // MIT License. See license.txt -if(!window.frappe) window.frappe = {}; +if (!window.frappe) window.frappe = {}; function flt(v, decimals, number_format) { - if(v==null || v=='')return 0; + if (v == null || v == '') return 0; - if(typeof v!=="number") { + if (typeof v !== "number") { v = v + ""; // strip currency symbol if exists - if(v.indexOf(" ")!=-1) { + if (v.indexOf(" ") != -1) { // using slice(1).join(" ") because space could also be a group separator - parts = v.split(" "); + var parts = v.split(" "); v = isNaN(parseFloat(parts[0])) ? parts.slice(parts.length - 1).join(" ") : v; } v = strip_number_groups(v, number_format); - v=parseFloat(v); - if(isNaN(v)) - v=0; + v = parseFloat(v); + if (isNaN(v)) + v = 0; } - if(decimals!=null) + if (decimals != null) return _round(v, decimals); return v; } function cint(v, def) { - if(v===true) + if (v === true) return 1; - if(v===false) + if (v === false) return 0; - v=v+''; - if(v!=="0")v=lstrip(v, ['0']); - v=parseInt(v); - if(isNaN(v))v=def===undefined?0:def; + v = v + ''; + if (v !== "0") v = lstrip(v, ['0']); + v = parseInt(v); + if (isNaN(v)) v = def === undefined ? 0 : def; return v; } function strip_number_groups(v, number_format) { - if(!number_format) number_format = get_number_format(); + if (!number_format) number_format = get_number_format(); var info = get_number_format_info(number_format); // strip groups (,) - var group_regex = new RegExp(info.group_sep==="." ? "\\." : info.group_sep, "g"); + var group_regex = new RegExp(info.group_sep === "." ? "\\." : info.group_sep, "g"); v = v.replace(group_regex, ""); // replace decimal separator with (.) - if (info.decimal_str!=="." && info.decimal_str!=="") { + if (info.decimal_str !== "." && info.decimal_str !== "") { var decimal_regex = new RegExp(info.decimal_str, "g"); v = v.replace(decimal_regex, "."); } @@ -59,32 +59,32 @@ function strip_number_groups(v, number_format) { frappe.number_format_info = { - "#,###.##": {decimal_str:".", group_sep:","}, - "#.###,##": {decimal_str:",", group_sep:"."}, - "# ###.##": {decimal_str:".", group_sep:" "}, - "# ###,##": {decimal_str:",", group_sep:" "}, - "#'###.##": {decimal_str:".", group_sep:"'"}, - "#, ###.##": {decimal_str:".", group_sep:", "}, - "#,##,###.##": {decimal_str:".", group_sep:","}, - "#,###.###": {decimal_str:".", group_sep:","}, - "#.###": {decimal_str:"", group_sep:"."}, - "#,###": {decimal_str:"", group_sep:","}, + "#,###.##": { decimal_str: ".", group_sep: "," }, + "#.###,##": { decimal_str: ",", group_sep: "." }, + "# ###.##": { decimal_str: ".", group_sep: " " }, + "# ###,##": { decimal_str: ",", group_sep: " " }, + "#'###.##": { decimal_str: ".", group_sep: "'" }, + "#, ###.##": { decimal_str: ".", group_sep: ", " }, + "#,##,###.##": { decimal_str: ".", group_sep: "," }, + "#,###.###": { decimal_str: ".", group_sep: "," }, + "#.###": { decimal_str: "", group_sep: "." }, + "#,###": { decimal_str: "", group_sep: "," }, } -window.format_number = function(v, format, decimals){ +window.format_number = function (v, format, decimals) { if (!format) { format = get_number_format(); - if(decimals == null) decimals = cint(frappe.defaults.get_default("float_precision")) || 3; + if (decimals == null) decimals = cint(frappe.defaults.get_default("float_precision")) || 3; } - info = get_number_format_info(format); + var info = get_number_format_info(format); // Fix the decimal first, toFixed will auto fill trailing zero. if (decimals == null) decimals = info.precision; v = flt(v, decimals, format); - if(v<0) var is_negative = true; + if (v < 0) var is_negative = true; v = Math.abs(v); v = v.toFixed(decimals); @@ -98,23 +98,23 @@ window.format_number = function(v, format, decimals){ var integer = part[0]; var str = ''; var offset = integer.length % group_position; - for (var i=integer.length; i>=0; i--) { + for (var i = integer.length; i >= 0; i--) { var l = replace_all(str, info.group_sep, "").length; - if(format=="#,##,###.##" && str.indexOf(",")!=-1) { // INR + if (format == "#,##,###.##" && str.indexOf(",") != -1) { // INR group_position = 2; l += 1; } str += integer.charAt(i); - if (l && !((l+1) % group_position) && i!=0 ) { + if (l && !((l + 1) % group_position) && i != 0) { str += info.group_sep; } } part[0] = str.split("").reverse().join(""); } - if(part[0]+""=="") { - part[0]="0"; + if (part[0] + "" == "") { + part[0] = "0"; } // join decimal @@ -131,18 +131,18 @@ function format_currency(v, currency, decimals) { decimals = frappe.boot.sysdefaults.currency_precision || null; } - if(symbol) + if (symbol) return symbol + " " + format_number(v, format, decimals); else return format_number(v, format, decimals); } function get_currency_symbol(currency) { - if(frappe.boot) { - if(frappe.boot.sysdefaults.hide_currency_symbol=="Yes") + if (frappe.boot) { + if (frappe.boot.sysdefaults.hide_currency_symbol == "Yes") return null; - if(!currency) + if (!currency) currency = frappe.boot.sysdefaults.currency; return frappe.model.get_value(":Currency", currency, "symbol") || currency; @@ -159,8 +159,8 @@ function get_number_format(currency) { function get_number_format_info(format) { var info = frappe.number_format_info[format]; - if(!info) { - info = {decimal_str:".", group_sep:","}; + if (!info) { + info = { decimal_str: ".", group_sep: "," }; } // get the precision from the number format @@ -171,13 +171,13 @@ function get_number_format_info(format) { function _round(num, precision) { var is_negative = num < 0 ? true : false; - var d = cint(precision); - var m = Math.pow(10, d); - var n = +(d ? Math.abs(num) * m : Math.abs(num)).toFixed(8); // Avoid rounding errors - var i = Math.floor(n), f = n - i; - var r = ((!precision && f == 0.5) ? ((i % 2 == 0) ? i : i + 1) : Math.round(n)); - r = d ? r / m : r; - return is_negative ? -r : r; + var d = cint(precision); + var m = Math.pow(10, d); + var n = +(d ? Math.abs(num) * m : Math.abs(num)).toFixed(8); // Avoid rounding errors + var i = Math.floor(n), f = n - i; + var r = ((!precision && f == 0.5) ? ((i % 2 == 0) ? i : i + 1) : Math.round(n)); + r = d ? r / m : r; + return is_negative ? -r : r; } @@ -187,20 +187,20 @@ function roundNumber(num, precision) { } function precision(fieldname, doc) { - if(cur_frm){ - if(!doc) doc = cur_frm.doc; + if (cur_frm) { + if (!doc) doc = cur_frm.doc; var df = frappe.meta.get_docfield(doc.doctype, fieldname, doc.parent || doc.name); - if(!df) console.log(fieldname + ": could not find docfield in method precision()"); + if (!df) console.log(fieldname + ": could not find docfield in method precision()"); return frappe.meta.get_field_precision(df, doc); - }else{ + } else { return frappe.boot.sysdefaults.float_precision } } function in_list(list, item) { - if(!list) return false; - for(var i=0, j=list.length; i(smallest_currency_fraction_value / 2)) { + if (remainder_val > (smallest_currency_fraction_value / 2)) { value += (smallest_currency_fraction_value - remainder_val); } else { value -= remainder_val; @@ -231,4 +231,4 @@ function round_based_on_smallest_currency_fraction(value, currency, precision) { value = Math.round(value); } return value; -}; +} diff --git a/frappe/public/js/frappe/misc/pretty_date.js b/frappe/public/js/frappe/misc/pretty_date.js index 7ec4c42ec1..faeb22f01b 100644 --- a/frappe/public/js/frappe/misc/pretty_date.js +++ b/frappe/public/js/frappe/misc/pretty_date.js @@ -1,28 +1,28 @@ // moment strings for translation -function prettyDate(time, mini){ - if(!time) { +function prettyDate(time, mini) { + if (!time) { time = new Date(); } - if(moment) { - if(window.sys_defaults && sys_defaults.time_zone) { - var ret = moment.tz(time, sys_defaults.time_zone).locale(frappe.boot.lang).fromNow(mini); + if (moment) { + if (frappe.sys_defaults && frappe.sys_defaults.time_zone) { + var ret = moment.tz(time, frappe.sys_defaults.time_zone).locale(frappe.boot.lang).fromNow(mini); } else { var ret = moment(time).locale(frappe.boot.lang).fromNow(mini); } - if(mini) { - if(ret === moment().locale(frappe.boot.lang).fromNow(mini)) { + if (mini) { + if (ret === moment().locale(frappe.boot.lang).fromNow(mini)) { ret = __("now"); } else { var parts = ret.split(" "); - if(parts.length > 1) { - if(parts[0]==="a" || parts[0]==="an") { + if (parts.length > 1) { + if (parts[0] === "a" || parts[0] === "an") { parts[0] = 1; } - if(parts[1].substr(0, 2)==="mo"){ + if (parts[1].substr(0, 2) === "mo") { ret = parts[0] + " M"; } else { - ret = parts[0] + " " + parts[1].substr(0, 1); + ret = parts[0] + " " + parts[1].substr(0, 1); } } } @@ -30,48 +30,50 @@ function prettyDate(time, mini){ } return ret; } else { - if(!time) return '' + if (!time) return '' var date = time; - if(typeof(time)=="string") - date = new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," ").replace(/\.[0-9]*/, "")); + if (typeof (time) == "string") + date = new Date((time || "").replace(/-/g, "/").replace(/[TZ]/g, " ").replace(/\.[0-9]*/, "")); var diff = (((new Date()).getTime() - date.getTime()) / 1000), - day_diff = Math.floor(diff / 86400); + day_diff = Math.floor(diff / 86400); - if ( isNaN(day_diff) || day_diff < 0 ) + if (isNaN(day_diff) || day_diff < 0) return ''; - return when = day_diff == 0 && ( - diff < 60 && __("just now") || - diff < 120 && __("1 minute ago") || - diff < 3600 && __("{0} minutes ago", [Math.floor( diff / 60 )]) || - diff < 7200 && __("1 hour ago") || - diff < 86400 && ("{0} hours ago", [Math.floor( diff / 3600 )])) || + var when = day_diff == 0 && ( + diff < 60 && __("just now") || + diff < 120 && __("1 minute ago") || + diff < 3600 && __("{0} minutes ago", [Math.floor(diff / 60)]) || + diff < 7200 && __("1 hour ago") || + diff < 86400 && ("{0} hours ago", [Math.floor(diff / 3600)])) || day_diff == 1 && __("Yesterday") || day_diff < 7 && __("{0} days ago", day_diff) || - day_diff < 31 && __("{0} weeks ago", [Math.ceil( day_diff / 7 )]) || - day_diff < 365 && __("{0} months ago", [Math.ceil( day_diff / 30)]) || - __("> {0} year(s) ago", [Math.floor( day_diff / 365 )]); + day_diff < 31 && __("{0} weeks ago", [Math.ceil(day_diff / 7)]) || + day_diff < 365 && __("{0} months ago", [Math.ceil(day_diff / 30)]) || + __("> {0} year(s) ago", [Math.floor(day_diff / 365)]); + + return when; } } -var comment_when = function(datetime, mini) { +var comment_when = function (datetime, mini) { var timestamp = frappe.datetime.str_to_user ? frappe.datetime.str_to_user(datetime) : datetime; return ' '; }; frappe.provide("frappe.datetime"); -frappe.datetime.refresh_when = function() { - if(jQuery) { - $(".frappe-timestamp").each(function() { +frappe.datetime.refresh_when = function () { + if (jQuery) { + $(".frappe-timestamp").each(function () { $(this).html(prettyDate($(this).attr("data-timestamp"), $(this).hasClass("mini"))); }); } } -setInterval(function() { frappe.datetime.refresh_when() }, 60000); // refresh every minute +setInterval(function () { frappe.datetime.refresh_when() }, 60000); // refresh every minute diff --git a/frappe/public/js/frappe/misc/tools.js b/frappe/public/js/frappe/misc/tools.js index 1414a5eee6..5e4ffc32e3 100644 --- a/frappe/public/js/frappe/misc/tools.js +++ b/frappe/public/js/frappe/misc/tools.js @@ -5,7 +5,7 @@ frappe.provide("frappe.tools"); frappe.tools.downloadify = function(data, roles, title) { if(roles && roles.length && !has_common(roles, roles)) { - msgprint(__("Export not allowed. You need {0} role to export.", [frappe.utils.comma_or(roles)])); + frappe.msgprint(__("Export not allowed. You need {0} role to export.", [frappe.utils.comma_or(roles)])); return; } diff --git a/frappe/public/js/frappe/misc/user.js b/frappe/public/js/frappe/misc/user.js index cc42a2f6ba..ee97b6889d 100644 --- a/frappe/public/js/frappe/misc/user.js +++ b/frappe/public/js/frappe/misc/user.js @@ -5,7 +5,7 @@ frappe.user_info = function(uid) { if(!uid) - uid = user; + uid = frappe.session.user; if(uid.toLowerCase()==="bot") { return { @@ -57,7 +57,7 @@ frappe.provide('frappe.user'); $.extend(frappe.user, { name: 'Guest', full_name: function(uid) { - return uid===user ? + return uid === frappe.session.user ? __("You") : frappe.user_info(uid).fullname; }, @@ -77,35 +77,29 @@ $.extend(frappe.user, { }, get_desktop_items: function() { // hide based on permission - modules_list = $.map(frappe.boot.desktop_icons, function(icon) { + var modules_list = $.map(frappe.boot.desktop_icons, function(icon) { var m = icon.module_name; var type = frappe.modules[m] && frappe.modules[m].type; if(frappe.boot.user.allow_modules.indexOf(m) === -1) return null; var ret = null; - switch(type) { - case "module": - if(frappe.boot.user.allow_modules.indexOf(m)!=-1 || frappe.modules[m].is_help) - ret = m; - break; - case "page": - if(frappe.boot.allowed_pages.indexOf(frappe.modules[m].link)!=-1) - ret = m; - break; - case "list": - if(frappe.model.can_read(frappe.modules[m]._doctype)) - ret = m; - break; - case "view": + if (type === "module") { + if(frappe.boot.user.allow_modules.indexOf(m)!=-1 || frappe.modules[m].is_help) ret = m; - break; - case "setup": - if(frappe.user.has_role("System Manager") || frappe.user.has_role("Administrator")) - ret = m; - break; - default: + } else if (type === "page") { + if(frappe.boot.allowed_pages.indexOf(frappe.modules[m].link)!=-1) ret = m; + } else if (type === "list") { + if(frappe.model.can_read(frappe.modules[m]._doctype)) + ret = m; + } else if (type === "view") { + ret = m; + } else if (type === "setup") { + if(frappe.user.has_role("System Manager") || frappe.user.has_role("Administrator")) + ret = m; + } else { + ret = m; } return ret; @@ -147,6 +141,19 @@ $.extend(frappe.user, { quote: quote }); } + }, + + /* Normally frappe.user is an object + * having properties and methods. + * But in the following case + * + * if (frappe.user === 'Administrator') + * + * frappe.user will cast to a string + * returning frappe.user.name + */ + toString: function() { + return this.name; } }); diff --git a/frappe/public/js/frappe/misc/utils.js b/frappe/public/js/frappe/misc/utils.js index 3cf3bca475..1ac16538fc 100644 --- a/frappe/public/js/frappe/misc/utils.js +++ b/frappe/public/js/frappe/misc/utils.js @@ -5,13 +5,13 @@ frappe.provide('frappe.utils'); frappe.utils = { get_random: function(len) { - var text = ""; - var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + var text = ""; + var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; - for( var i=0; i < len; i++ ) - text += possible.charAt(Math.floor(Math.random() * possible.length)); + for( var i=0; i < len; i++ ) + text += possible.charAt(Math.floor(Math.random() * possible.length)); - return text; + return text; }, get_file_link: function(filename) { filename = cstr(filename); @@ -122,7 +122,7 @@ frappe.utils = { return [dict[filters]] } $.each(dict, function(i, d) { - for(key in filters) { + for(var key in filters) { if($.isArray(filters[key])) { if(filters[key][0]=="in") { if(filters[key][1].indexOf(d[key])==-1) @@ -242,7 +242,6 @@ frappe.utils = { break; default: return false; - break; } // test regExp if not null @@ -288,7 +287,7 @@ frappe.utils = { }; if(!compare_type) - compare_type = typeof list[0][key]==="string" ? "string" : "number"; + compare_type = typeof list[0][key]==="string" ? "string" : "number"; list.sort(sort_fn[compare_type]); @@ -349,20 +348,20 @@ frappe.utils = { if (!arr1 || !arr2) { return false; } - if (arr1.length != arr2.length) { + if (arr1.length != arr2.length) { return false; } - for (var i = 0; i < arr1.length; i++) { - if ($.isArray(arr1[i])) { - if (!frappe.utils.arrays_equal(arr1[i], arr2[i])) { + for (var i = 0; i < arr1.length; i++) { + if ($.isArray(arr1[i])) { + if (!frappe.utils.arrays_equal(arr1[i], arr2[i])) { return false; } - } - else if (arr1[i] !== arr2[i]) { + } + else if (arr1[i] !== arr2[i]) { return false; } - } - return true; + } + return true; }, intersection: function(a, b) { @@ -411,13 +410,13 @@ frappe.utils = { var tempH = tempImg.height; if (tempW > tempH) { if (tempW > max_width) { - tempH *= max_width / tempW; - tempW = max_width; + tempH *= max_width / tempW; + tempW = max_width; } } else { if (tempH > max_height) { - tempW *= max_height / tempH; - tempH = max_height; + tempW *= max_height / tempH; + tempH = max_height; } } @@ -431,88 +430,88 @@ frappe.utils = { } }, - csv_to_array: function (strData, strDelimiter) { - // Check to see if the delimiter is defined. If not, - // then default to comma. - strDelimiter = (strDelimiter || ","); + csv_to_array: function (strData, strDelimiter) { + // Check to see if the delimiter is defined. If not, + // then default to comma. + strDelimiter = (strDelimiter || ","); - // Create a regular expression to parse the CSV values. - var objPattern = new RegExp( - ( - // Delimiters. - "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" + + // Create a regular expression to parse the CSV values. + var objPattern = new RegExp( + ( + // Delimiters. + "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" + - // Quoted fields. - "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" + + // Quoted fields. + "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" + - // Standard fields. - "([^\"\\" + strDelimiter + "\\r\\n]*))" - ), - "gi" - ); + // Standard fields. + "([^\"\\" + strDelimiter + "\\r\\n]*))" + ), + "gi" + ); - // Create an array to hold our data. Give the array - // a default empty first row. - var arrData = [[]]; + // Create an array to hold our data. Give the array + // a default empty first row. + var arrData = [[]]; - // Create an array to hold our individual pattern - // matching groups. - var arrMatches = null; + // Create an array to hold our individual pattern + // matching groups. + var arrMatches = null; - // Keep looping over the regular expression matches - // until we can no longer find a match. - while (arrMatches = objPattern.exec( strData )){ + // Keep looping over the regular expression matches + // until we can no longer find a match. + while ((arrMatches = objPattern.exec( strData ))){ - // Get the delimiter that was found. - var strMatchedDelimiter = arrMatches[ 1 ]; + // Get the delimiter that was found. + var strMatchedDelimiter = arrMatches[ 1 ]; - // Check to see if the given delimiter has a length - // (is not the start of string) and if it matches - // field delimiter. If id does not, then we know - // that this delimiter is a row delimiter. - if ( - strMatchedDelimiter.length && - strMatchedDelimiter !== strDelimiter - ){ + // Check to see if the given delimiter has a length + // (is not the start of string) and if it matches + // field delimiter. If id does not, then we know + // that this delimiter is a row delimiter. + if ( + strMatchedDelimiter.length && + strMatchedDelimiter !== strDelimiter + ){ - // Since we have reached a new row of data, - // add an empty row to our data array. - arrData.push( [] ); + // Since we have reached a new row of data, + // add an empty row to our data array. + arrData.push( [] ); - } + } - var strMatchedValue; + var strMatchedValue; - // Now that we have our delimiter out of the way, - // let's check to see which kind of value we - // captured (quoted or unquoted). - if (arrMatches[ 2 ]){ + // Now that we have our delimiter out of the way, + // let's check to see which kind of value we + // captured (quoted or unquoted). + if (arrMatches[ 2 ]){ - // We found a quoted value. When we capture - // this value, unescape any double quotes. - strMatchedValue = arrMatches[ 2 ].replace( - new RegExp( "\"\"", "g" ), - "\"" - ); + // We found a quoted value. When we capture + // this value, unescape any double quotes. + strMatchedValue = arrMatches[ 2 ].replace( + new RegExp( "\"\"", "g" ), + "\"" + ); - } else { + } else { - // We found a non-quoted value. - strMatchedValue = arrMatches[ 3 ]; + // We found a non-quoted value. + strMatchedValue = arrMatches[ 3 ]; - } + } - // Now that we have our value string, let's add - // it to the data array. - arrData[ arrData.length - 1 ].push( strMatchedValue ); - } + // Now that we have our value string, let's add + // it to the data array. + arrData[ arrData.length - 1 ].push( strMatchedValue ); + } - // Return the parsed data. - return( arrData ); - }, + // Return the parsed data. + return( arrData ); + }, warn_page_name_change: function(frm) { frappe.msgprint("Note: Changing the Page Name will break previous URL to this page."); @@ -588,42 +587,42 @@ frappe.utils = { // String.prototype.includes polyfill // https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/includes if (!String.prototype.includes) { - String.prototype.includes = function(search, start) { - 'use strict'; - if (typeof start !== 'number') { - start = 0; - } - if (start + search.length > this.length) { - return false; - } else { - return this.indexOf(search, start) !== -1; - } - }; + String.prototype.includes = function (search, start) { + 'use strict'; + if (typeof start !== 'number') { + start = 0; + } + if (start + search.length > this.length) { + return false; + } else { + return this.indexOf(search, start) !== -1; + } + }; } // Array.prototype.includes polyfill // https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/includes if (!Array.prototype.includes) { - Object.defineProperty(Array.prototype, 'includes', { - value: function(searchElement, fromIndex) { - if (this == null) { - throw new TypeError('"this" is null or not defined'); - } - var o = Object(this); - var len = o.length >>> 0; - if (len === 0) { - return false; - } - var n = fromIndex | 0; - var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); - while (k < len) { - if (o[k] === searchElement) { - return true; - } - k++; - } - return false; - } - }); + Object.defineProperty(Array.prototype, 'includes', { + value: function(searchElement, fromIndex) { + if (this == null) { + throw new TypeError('"this" is null or not defined'); + } + var o = Object(this); + var len = o.length >>> 0; + if (len === 0) { + return false; + } + var n = fromIndex | 0; + var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); + while (k < len) { + if (o[k] === searchElement) { + return true; + } + k++; + } + return false; + } + }); } // Array de duplicate if (!Array.prototype.uniqBy) { diff --git a/frappe/public/js/frappe/model/create_new.js b/frappe/public/js/frappe/model/create_new.js index be1ec9bb4f..2448734dbe 100644 --- a/frappe/public/js/frappe/model/create_new.js +++ b/frappe/public/js/frappe/model/create_new.js @@ -15,7 +15,7 @@ $.extend(frappe.model, { name: frappe.model.get_new_name(doctype), __islocal: 1, __unsaved: 1, - owner: user + owner: frappe.session.user }; frappe.model.set_default_values(doc, parent_doc); @@ -103,7 +103,8 @@ $.extend(frappe.model, { updated.push(f.fieldname); } else if(f.fieldtype == "Select" && f.options && typeof f.options === 'string' && !in_list(["[Select]", "Loading..."], f.options)) { - doc[f.fieldname] = f.options.split("\n")[0]; + + doc[f.fieldname] = f.options.split("\n")[0]; } } } @@ -140,7 +141,7 @@ $.extend(frappe.model, { if(!df.ignore_user_permissions) { // 2 - look in user defaults - user_defaults = frappe.defaults.get_user_defaults(df.options); + var user_defaults = frappe.defaults.get_user_defaults(df.options); if (user_defaults && user_defaults.length===1) { // Use User Permission value when only when it has a single value user_default = user_defaults[0]; @@ -171,13 +172,13 @@ $.extend(frappe.model, { return frappe.session.user; } else if (df["default"] == "user_fullname") { - return user_fullname; + return frappe.session.user_fullname; } else if (df["default"] == "Today") { - return dateutil.get_today(); + return frappe.datetime.get_today(); } else if ((df["default"] || "").toLowerCase() === "now") { - return dateutil.now_datetime(); + return frappe.datetime.now_datetime(); } else if (df["default"][0]===":") { var boot_doc = frappe.model.get_default_from_boot_docs(df, doc, parent_doc); @@ -198,7 +199,7 @@ $.extend(frappe.model, { } } else if (df.fieldtype=="Time") { - return dateutil.now_time(); + return frappe.datetime.now_time(); } }, @@ -252,21 +253,24 @@ $.extend(frappe.model, { // dont copy name and blank fields var df = frappe.meta.get_docfield(doc.doctype, key); - if(df && key.substr(0,2)!='__' + if (df && key.substr(0, 2) != '__' && !in_list(no_copy_list, key) - && !(df && (!from_amend && cint(df.no_copy)==1))) { - var value = doc[key] || []; - if(df.fieldtype==="Table") { - for(var i=0, j=value.length; iicon - for(key in perm) { + for(var key in perm) { if(key!='parent' && key!='permlevel') { if(perm[key]) { perm[key] = ''; diff --git a/frappe/public/js/frappe/router.js b/frappe/public/js/frappe/router.js index 3f6ddba9b8..7a58076a60 100644 --- a/frappe/public/js/frappe/router.js +++ b/frappe/public/js/frappe/router.js @@ -120,7 +120,7 @@ frappe.set_route = function() { if(params.length===1 && $.isArray(params[0])) { params = params[0]; } - route = $.map(params, function(a) { + var route = $.map(params, function(a) { if($.isPlainObject(a)) { frappe.route_options = a; return null; diff --git a/frappe/public/js/frappe/socketio_client.js b/frappe/public/js/frappe/socketio_client.js index f3b028cca9..c8af253bed 100644 --- a/frappe/public/js/frappe/socketio_client.js +++ b/frappe/public/js/frappe/socketio_client.js @@ -18,7 +18,7 @@ frappe.socket = { //Enable secure option when using HTTPS if (window.location.protocol == "https:") { - frappe.socket.socket = io.connect(frappe.socket.get_host(), {secure: true}); + frappe.socket.socket = io.connect(frappe.socket.get_host(), {secure: true}); } else if (window.location.protocol == "http:") { frappe.socket.socket = io.connect(frappe.socket.get_host()); diff --git a/frappe/public/js/frappe/toolbar.js b/frappe/public/js/frappe/toolbar.js index 3e712c40c9..55f8dc2f2e 100755 --- a/frappe/public/js/frappe/toolbar.js +++ b/frappe/public/js/frappe/toolbar.js @@ -56,8 +56,8 @@ frappe.get_form_sidebar_extension = function() { var template = '{{ usage.total }}MB ({{ usage.total_used_percent }}%) used\ + '; usage.sidebar_usage_html = frappe.render(template, { 'usage': usage }, "form_sidebar_usage"); } else { diff --git a/frappe/public/js/frappe/translate.js b/frappe/public/js/frappe/translate.js index 7a54bde034..bc9acd497f 100644 --- a/frappe/public/js/frappe/translate.js +++ b/frappe/public/js/frappe/translate.js @@ -8,7 +8,7 @@ frappe._ = function(txt, replace) { return txt; if(typeof(txt) != "string") return txt; - ret = frappe._messages[txt.replace(/\n/g, "")] || txt; + var ret = frappe._messages[txt.replace(/\n/g, "")] || txt; if(replace && typeof(replace) === "object") { ret = $.format(ret, replace); } diff --git a/frappe/public/js/frappe/ui/base_list.js b/frappe/public/js/frappe/ui/base_list.js index d28e040ecf..720144350b 100644 --- a/frappe/public/js/frappe/ui/base_list.js +++ b/frappe/public/js/frappe/ui/base_list.js @@ -173,7 +173,7 @@ frappe.ui.BaseList = Class.extend({ // default filter for submittable doctype if (frappe.model.is_submittable(this.doctype)) { this.filter_list.add_filter(this.doctype, "docstatus", "!=", 2); - }; + } }, clear: function () { diff --git a/frappe/public/js/frappe/ui/charts.js b/frappe/public/js/frappe/ui/charts.js index 776e35fdb3..054f1bdc36 100644 --- a/frappe/public/js/frappe/ui/charts.js +++ b/frappe/public/js/frappe/ui/charts.js @@ -18,8 +18,8 @@ frappe.ui.Chart = Class.extend({ if(this.opts.data && ((this.opts.data.columns && this.opts.data.columns.length >= 1) || (this.opts.data.rows && this.opts.data.rows.length >= 1))) { - this.chart = this.render_chart(); - this.show_chart(true); + this.chart = this.render_chart(); + this.show_chart(true); } return this.chart; @@ -28,11 +28,11 @@ frappe.ui.Chart = Class.extend({ render_chart: function() { var chart_dict = { bindto: '#' + this.opts.bind_to, - data: {}, + data: {}, axis: { - x: { - type: this.opts.x_type || 'category' // this needed to load string x value - }, + x: { + type: this.opts.x_type || 'category' // this needed to load string x value + }, y: { padding: { bottom: 10 } } @@ -62,11 +62,11 @@ frappe.ui.Chart = Class.extend({ chart_dict.axis.x.tick.culling = {max: 15}; chart_dict.axis.x.tick.format = frappe.boot.sysdefaults.date_format .replace('yyyy', '%Y').replace('mm', '%m').replace('dd', '%d'); - }; + } // set color if(!chart_dict.data.colors && chart_dict.data.columns) { - colors = ['#4E50A6', '#7679FB', '#A3A5FC', '#925191', '#5D3EA4', '#8D5FFA', + var colors = ['#4E50A6', '#7679FB', '#A3A5FC', '#925191', '#5D3EA4', '#8D5FFA', '#5E3AA8', '#7B933D', '#4F8EA8']; chart_dict.data.colors = {}; chart_dict.data.columns.forEach(function(d, i) { diff --git a/frappe/public/js/frappe/ui/field_group.js b/frappe/public/js/frappe/ui/field_group.js index e40b6d87f5..896dca5901 100644 --- a/frappe/public/js/frappe/ui/field_group.js +++ b/frappe/public/js/frappe/ui/field_group.js @@ -74,7 +74,7 @@ frappe.ui.FieldGroup = frappe.ui.form.Layout.extend({ } } if(errors.length && !ignore_errors) { - msgprint({ + frappe.msgprint({ title: __('Missing Values Required'), message: __('Following fields have missing values:') + ' '; +', @@ -106,7 +106,7 @@ frappe.ui.FieldGroup = frappe.ui.form.Layout.extend({ } }, clear: function() { - for(key in this.fields_dict) { + for(var key in this.fields_dict) { var f = this.fields_dict[key]; if(f && f.set_input) { f.set_input(f.df['default'] || ''); diff --git a/frappe/public/js/frappe/ui/filters/filters.js b/frappe/public/js/frappe/ui/filters/filters.js index 263fdf89b6..ea812a751a 100644 --- a/frappe/public/js/frappe/ui/filters/filters.js +++ b/frappe/public/js/frappe/ui/filters/filters.js @@ -105,7 +105,7 @@ frappe.ui.FilterList = Class.extend({ // This gives a predictable stats order me.wrapper.find(".filter-stat").empty(); $.each(me.stats, function (i, v) { - me.render_filters(v, (r.message|| {})[v.name]); + me.render_filters(v, (r.message|| {})[v.name]); }); } }); @@ -149,8 +149,8 @@ frappe.ui.FilterList = Class.extend({ } if(options.length>0) { - for (i in stat) { - for (o in options) { + for (var i in stat) { + for (var o in options) { if (stat[i][0] == options[o].value) { if (field.name=="docstatus") { labels[i] = options[o].label @@ -353,7 +353,7 @@ frappe.ui.FilterList = Class.extend({ fieldname: fieldname, condition: condition, value: value - }); + }); this.filters.push(filter); @@ -460,8 +460,7 @@ frappe.ui.Filter = Class.extend({ ? __("values separated by commas") : __("use % as wildcard"))+'
- ' + errors.join('
- ') + '
') .appendTo(dialog.body); - dialog.progress_bar = dialog.progress.css({"margin-top": "10px"}) - .find(".progress-bar"); + dialog.progress_bar = dialog.progress.css({"margin-top": "10px"}) + .find(".progress-bar"); dialog.$wrapper.removeClass("fade"); dialog.show(); frappe.cur_progress = dialog; @@ -260,6 +259,7 @@ frappe.show_alert = function(message, seconds=7) { $('').appendTo('body'); } + var message_html; if(message.indicator) { message_html = $('').append(message.message); } else { @@ -286,5 +286,3 @@ frappe.show_alert = function(message, seconds=7) { return div; } -// for backward compatibility -var show_alert = frappe.show_alert; diff --git a/frappe/public/js/frappe/ui/page.js b/frappe/public/js/frappe/ui/page.js index 3b7a6939c4..f6ac7e241e 100644 --- a/frappe/public/js/frappe/ui/page.js +++ b/frappe/public/js/frappe/ui/page.js @@ -317,7 +317,7 @@ frappe.ui.Page = Class.extend({ return this.$title_area.find(".title-icon") .html(' ') .toggle(true); - }, + }, add_help_button: function(txt) { // diff --git a/frappe/public/js/frappe/ui/toolbar/about.js b/frappe/public/js/frappe/ui/toolbar/about.js index c0c1dae138..3ef036ad5f 100644 --- a/frappe/public/js/frappe/ui/toolbar/about.js +++ b/frappe/public/js/frappe/ui/toolbar/about.js @@ -6,8 +6,8 @@ frappe.ui.misc.about = function() { $(d.body).html(repl("\"+__("Open Source Applications for the Web")+"
\\ - Website: https://frappe.io
\ -\ + Website: https://frappe.io
\ +\ Source: https://github.com/frappe
\
\Installed Apps
\ @@ -31,14 +31,14 @@ frappe.ui.misc.about = function() { var show_versions = function(versions) { var $wrap = $("#about-app-versions").empty(); - $.each(keys(versions).sort(), function(i, key) { + $.each(Object.keys(versions).sort(), function(i, key) { var v = versions[key]; if(v.branch) { var text = $.format('{0}: v{1} ({2})
', - [v.title, v.branch_version || v.version, v.branch]) + [v.title, v.branch_version || v.version, v.branch]) } else { var text = $.format('{0}: v{1}
', - [v.title, v.version]) + [v.title, v.version]) } $(text).appendTo($wrap); }); diff --git a/frappe/public/js/frappe/ui/toolbar/awesome_bar.js b/frappe/public/js/frappe/ui/toolbar/awesome_bar.js index ed9b7c27dd..e54833f846 100644 --- a/frappe/public/js/frappe/ui/toolbar/awesome_bar.js +++ b/frappe/public/js/frappe/ui/toolbar/awesome_bar.js @@ -138,7 +138,7 @@ frappe.search.AwesomeBar = Class.extend({\ ' - msgprint(txt, __("Search Help")); + frappe.msgprint(txt, __("Search Help")); } }); }, @@ -255,7 +255,7 @@ frappe.search.AwesomeBar = Class.extend({ index: 80, default: "Calculator", onclick: function() { - msgprint(formatted_value, "Result"); + frappe.msgprint(formatted_value, "Result"); } }); } catch(e) { diff --git a/frappe/public/js/frappe/ui/toolbar/notifications.js b/frappe/public/js/frappe/ui/toolbar/notifications.js index 5b5abc9b79..9198594d8e 100644 --- a/frappe/public/js/frappe/ui/toolbar/notifications.js +++ b/frappe/public/js/frappe/ui/toolbar/notifications.js @@ -2,9 +2,9 @@ frappe.provide("frappe.ui.notifications") frappe.ui.notifications.update_notifications = function() { frappe.ui.notifications.total = 0; - var doctypes = keys(frappe.boot.notification_info.open_count_doctype).sort(); - var modules = keys(frappe.boot.notification_info.open_count_module).sort(); - var other = keys(frappe.boot.notification_info.open_count_other).sort(); + var doctypes = Object.keys(frappe.boot.notification_info.open_count_doctype).sort(); + var modules = Object.keys(frappe.boot.notification_info.open_count_module).sort(); + var other = Object.keys(frappe.boot.notification_info.open_count_other).sort(); // clear toolbar / sidebar notifications frappe.ui.notifications.dropdown_notification = $("#dropdown-notification").empty(); diff --git a/frappe/public/js/frappe/ui/toolbar/search.js b/frappe/public/js/frappe/ui/toolbar/search.js index e2c0e67430..dec4f38795 100644 --- a/frappe/public/js/frappe/ui/toolbar/search.js +++ b/frappe/public/js/frappe/ui/toolbar/search.js @@ -57,7 +57,7 @@ frappe.search.SearchDialog = Class.extend({ clearTimeout($this.data('timeout')); $this.data('timeout', setTimeout(function() { if(me.$input.val() === me.current_keyword) return; - keywords = me.$input.val(); + var keywords = me.$input.val(); if(keywords.length > 1) { me.get_results(keywords); } else { @@ -102,12 +102,12 @@ frappe.search.SearchDialog = Class.extend({ frappe.search.utils.get_global_results(me.current_keyword, current_count, me.more_count, type) .then(function(doctype_results) { - me.add_more_results(doctype_results); + me.add_more_results(doctype_results); }, function (err) { console.error(err); }); } else { - results = me.nav_lists[type].slice(0, me.more_count); + var results = me.nav_lists[type].slice(0, me.more_count); me.nav_lists[type].splice(0, me.more_count); me.add_more_results([{title: type, results: results}]); } @@ -133,6 +133,7 @@ frappe.search.SearchDialog = Class.extend({ if(me.$modal_body.find('.list-link').length > 1) { if(me.modal_state === 0) { // DOWN and UP keys navigate sidebar + var { UP_ARROW, DOWN_ARROW, TAB } = frappe.ui.keyCode; if(e.which === DOWN_ARROW || e.which === TAB) { e.preventDefault(); var $link = me.$modal_body.find('.list-link.select').next(); @@ -247,7 +248,7 @@ frappe.search.SearchDialog = Class.extend({ are_expansive = true; break; } - }; + } if(results[0].image) margin_more = "20px"; var [section_length, col_width] = are_expansive ? [3, "12"] : [4, "6"]; diff --git a/frappe/public/js/frappe/ui/toolbar/search_utils.js b/frappe/public/js/frappe/ui/toolbar/search_utils.js index 2148a88ed9..a985f9ba96 100644 --- a/frappe/public/js/frappe/ui/toolbar/search_utils.js +++ b/frappe/public/js/frappe/ui/toolbar/search_utils.js @@ -5,27 +5,27 @@ frappe.search.utils = { this.recent = JSON.parse(frappe.boot.user.recent || "[]") || []; }, - get_recent_pages: function(keywords) { - var me = this; - values = [], options = []; - function find(list, keywords, process) { - list.forEach(function(item, i) { - _item = ($.isArray(item)) ? item[0] : item; - _item = __(_item || '').toLowerCase().replace(/-/g, " "); - - if(keywords===_item || _item.indexOf(keywords) !== -1) { - var option = process(item); - - if(option) { - if($.isPlainObject(option)) { - option = [option]; - } - option.forEach(function(o) { o.match = item; }); - options = option.concat(options); - } - } - }); - } + get_recent_pages: function(keywords) { + var me = this, values = [], options = []; + + function find(list, keywords, process) { + list.forEach(function(item, i) { + var _item = ($.isArray(item)) ? item[0] : item; + _item = __(_item || '').toLowerCase().replace(/-/g, " "); + + if(keywords===_item || _item.indexOf(keywords) !== -1) { + var option = process(item); + + if(option) { + if($.isPlainObject(option)) { + option = [option]; + } + option.forEach(function(o) { o.match = item; }); + options = option.concat(options); + } + } + }); + } me.recent.forEach(function(doctype, i) { values.push([doctype[1], ['Form', doctype[0], doctype[1]]]); @@ -48,7 +48,7 @@ frappe.search.utils = { }); find(values, keywords, function(match) { - out = { + var out = { route: match[1] } if(match[1][0]==='Form') { @@ -73,35 +73,35 @@ frappe.search.utils = { return out; }); - return options; + return options; }, - get_search_in_list: function(keywords) { - var me = this; + get_search_in_list: function(keywords) { + var me = this; var out = []; if(in_list(keywords.split(" "), "in") && (keywords.slice(-2) !== "in")) { - parts = keywords.split(" in "); + var parts = keywords.split(" in "); frappe.boot.user.can_read.forEach(function (item) { if(frappe.boot.user.can_search.includes(item)) { - var level = me.fuzzy_search(parts[1], item); - if(level) { - out.push({ - type: "In List", - label: __('Find {0} in {1}', [__(parts[0]), me.bolden_match_part(__(item), parts[1])]), - value: __('Find {0} in {1}', [__(parts[0]), __(item)]), - route_options: {"name": ["like", "%" + parts[0] + "%"]}, - index: 1 + level, - route: ["List", item] - }); - } - } + var level = me.fuzzy_search(parts[1], item); + if(level) { + out.push({ + type: "In List", + label: __('Find {0} in {1}', [__(parts[0]), me.bolden_match_part(__(item), parts[1])]), + value: __('Find {0} in {1}', [__(parts[0]), __(item)]), + route_options: {"name": ["like", "%" + parts[0] + "%"]}, + index: 1 + level, + route: ["List", item] + }); + } + } }); } return out; - }, + }, - get_creatables: function(keywords) { - var me = this; + get_creatables: function(keywords) { + var me = this; var out = []; if(keywords.split(" ")[0]==="new") { frappe.boot.user.can_create.forEach(function (item) { @@ -119,10 +119,10 @@ frappe.search.utils = { }); } return out; - }, + }, - get_doctypes: function(keywords) { - var me = this; + get_doctypes: function(keywords) { + var me = this; var out = []; var level, target; @@ -136,49 +136,49 @@ frappe.search.utils = { route: route, } }; - frappe.boot.user.can_read.forEach(function(item) { - level = me.fuzzy_search(keywords, item); - if(level) { - target = item; - if(in_list(frappe.boot.single_types, item)) { - out.push(option("", ["Form", item, item], 0.05)); - - } else if(frappe.boot.user.can_search.includes(item)) { - // include 'making new' option - if(in_list(frappe.boot.user.can_create, item)) { - var match = item; - out.push({ - type: "New", - label: __("New {0}", [me.bolden_match_part(__(item), keywords)]), - value: __("New {0}", [__(item)]), - index: level + 0.01, - match: item, - onclick: function() { frappe.new_doc(match, true); } - }); - } - if(in_list(frappe.boot.treeviews, item)) { - out.push(option("Tree", ["Tree", item], 0.05)); - - } else { - out.push(option("List", ["List", item], 0.05)); - if(frappe.model.can_get_report(item)) { - out.push(option("Report", ["Report", item], 0.04)); - } - if(frappe.boot.calendars.indexOf(item) !== -1) { - out.push(option("Calendar", ["List", item, "Calendar"], 0.03)); - out.push(option("Gantt", ["List", item, "Gantt"], 0.02)); - } - } - } - } + frappe.boot.user.can_read.forEach(function (item) { + level = me.fuzzy_search(keywords, item); + if (level) { + target = item; + if (in_list(frappe.boot.single_types, item)) { + out.push(option("", ["Form", item, item], 0.05)); + + } else if (frappe.boot.user.can_search.includes(item)) { + // include 'making new' option + if (in_list(frappe.boot.user.can_create, item)) { + var match = item; + out.push({ + type: "New", + label: __("New {0}", [me.bolden_match_part(__(item), keywords)]), + value: __("New {0}", [__(item)]), + index: level + 0.01, + match: item, + onclick: function () { frappe.new_doc(match, true); } + }); + } + if (in_list(frappe.boot.treeviews, item)) { + out.push(option("Tree", ["Tree", item], 0.05)); + + } else { + out.push(option("List", ["List", item], 0.05)); + if (frappe.model.can_get_report(item)) { + out.push(option("Report", ["Report", item], 0.04)); + } + if (frappe.boot.calendars.indexOf(item) !== -1) { + out.push(option("Calendar", ["List", item, "Calendar"], 0.03)); + out.push(option("Gantt", ["List", item, "Gantt"], 0.02)); + } + } + } + } }); return out; - }, + }, - get_reports: function(keywords) { - var me = this; + get_reports: function(keywords) { + var me = this; var out = []; - var route; + var route; Object.keys(frappe.boot.user.all_reports).forEach(function(item) { var level = me.fuzzy_search(keywords, item); if(level > 0) { @@ -188,7 +188,7 @@ frappe.search.utils = { else route = ["query-report", item]; out.push({ - type: "Report", + type: "Report", label: __("Report {0}" , [me.bolden_match_part(__(item), keywords)]), value: __("Report {0}" , [__(item)]), index: level, @@ -197,10 +197,10 @@ frappe.search.utils = { } }); return out; - }, + }, - get_pages: function(keywords) { - var me = this; + get_pages: function(keywords) { + var me = this; var out = []; this.pages = {}; $.each(frappe.boot.page_info, function(name, p) { @@ -221,8 +221,8 @@ frappe.search.utils = { }); } }); - var target = 'Calendar'; - if(__('calendar').indexOf(keywords.toLowerCase()) === 0) { + var target = 'Calendar'; + if(__('calendar').indexOf(keywords.toLowerCase()) === 0) { out.push({ type: "Calendar", value: __("Open {0}", [__(target)]), @@ -231,7 +231,7 @@ frappe.search.utils = { route: ['List', 'Event', target], }); } - if(__('email inbox').indexOf(keywords.toLowerCase()) === 0) { + if(__('email inbox').indexOf(keywords.toLowerCase()) === 0) { out.push({ type: "Inbox", value: __("Open {0}", [__('Email Inbox')]), @@ -241,17 +241,17 @@ frappe.search.utils = { }); } return out; - }, + }, - get_modules: function(keywords) { - var me = this; + get_modules: function(keywords) { + var me = this; var out = []; Object.keys(frappe.modules).forEach(function(item) { var level = me.fuzzy_search(keywords, item); if(level > 0) { var module = frappe.modules[item]; if(module._doctype) return; - ret = { + var ret = { type: "Module", label: __("Open {0}", [me.bolden_match_part(__(item), keywords)]), value: __("Open {0}", [__(item)]), @@ -266,196 +266,196 @@ frappe.search.utils = { } }); return out; - }, - - get_global_results: function (keywords, start, limit, doctype = "") { - var me = this; - function get_results_sets(data) { - var results_sets = [], result, set; - function get_existing_set (doctype) { - return results_sets.find(function(set) { - return set.title === doctype; - }); - } - - function make_description(content, doc_name) { - var parts = content.split(" ||| "); - var result_max_length = 300; - var field_length = 120; - var fields = []; - var result_current_length = 0; - var field_text = ""; - for(var i = 0; i < parts.length; i++) { - part = parts[i]; - if(part.toLowerCase().indexOf(keywords) !== -1) { - // If the field contains the keyword - if(part.indexOf(' &&& ') !== -1) { - var colon_index = part.indexOf(' &&& '); - var field_value = part.slice(colon_index + 5); - } else { - var colon_index = part.indexOf(' : '); - var field_value = part.slice(colon_index + 3); - } - if(field_value.length > field_length) { - // If field value exceeds field_length, find the keyword in it - // and trim field value by half the field_length at both sides - // ellipsify if necessary - var field_data = ""; - var index = field_value.indexOf(keywords); - field_data += index < field_length/2 ? field_value.slice(0, index) - : '...' + field_value.slice(index - field_length/2, index) - field_data += field_value.slice(index, index + field_length/2); - field_data += index + field_length/2 < field_value.length ? "..." : ""; - field_value = field_data; - } - var field_name = part.slice(0, colon_index); - - // Find remaining result_length and add field length to result_current_length - var remaining_length = result_max_length - result_current_length; - result_current_length += field_name.length + field_value.length + 2; - if(result_current_length < result_max_length) { - // We have room, push the entire field - field_text = '' + - me.bolden_match_part(field_name, keywords) + ': ' + - me.bolden_match_part(field_value, keywords); - if(fields.indexOf(field_text) === -1 && doc_name !== field_value) { - fields.push(field_text); - } - } else { - // Not enough room - if(field_name.length < remaining_length){ - // Ellipsify (trim at word end) and push - remaining_length -= field_name.length; - field_text = '' + - me.bolden_match_part(field_name, keywords) + ': '; - field_value = field_value.slice(0, remaining_length); - field_value = field_value.slice(0, field_value.lastIndexOf(' ')) + ' ...'; - field_text += me.bolden_match_part(field_value, keywords); - fields.push(field_text); - } else { - // No room for even the field name, skip - fields.push('...'); - } - break; - } - } - } - return fields.join(', '); - } - - data.forEach(function(d) { - // more properties - result = { - label: d.name, - value: d.name, - description: make_description(d.content, d.name), - route: ['Form', d.doctype, d.name], - } - if(d.image || d.image === null){ - result.image = d.image; - } - set = get_existing_set(d.doctype); - if(set) { - set.results.push(result); - } else { - set = { - title: d.doctype, - results: [result], - fetch_type: "Global" - } - results_sets.push(set); - } - - }); - return results_sets; - } - return new Promise(function(resolve, reject) { - frappe.call({ - method: "frappe.utils.global_search.search", - args: { - text: keywords, - start: start, - limit: limit, - doctype: doctype - }, - callback: function(r) { - if(r.message) { - resolve(get_results_sets(r.message)); - } else { - resolve([]); - } - } - }); - }); - }, - - get_help_results: function(keywords) { - function get_results_set(data) { - var result; - var set = { - title: "Help", - fetch_type: "Help", - results: [] - } - data.forEach(function(d) { - // more properties - result = { - label: d[0], - value: d[0], - description: d[1], - data_path: d[2], - onclick: function() { - - } - } - set.results.push(result); - }); - return [set]; - } - return new Promise(function(resolve, reject) { - frappe.call({ - method: "frappe.utils.help.get_help", - args: { - text: keywords - }, - callback: function(r) { - if(r.message) { - resolve(get_results_set(r.message)); - } else { - resolve([]); - } - } - }); - }); - }, - - get_nav_results: function(keywords) { - function sort_uniques(array) { - var routes = [], out = []; - array.forEach(function(d) { - if(d.route) { - if(d.route[0] === "List" && d.route[2]) { - d.route.splice(2); - } - var str_route = d.route.join('/'); - if(routes.indexOf(str_route) === -1) { - routes.push(str_route); - out.push(d); - } else { - var old = routes.indexOf(str_route); - if(out[old].index > d.index) { - out[old] = d; - } - } - } else { - out.push(d); - } - }); - return out.sort(function(a, b) { - return b.index - a.index; - }); - } - var lists = [], setup = []; + }, + + get_global_results: function (keywords, start, limit, doctype = "") { + var me = this; + function get_results_sets(data) { + var results_sets = [], result, set; + function get_existing_set (doctype) { + return results_sets.find(function(set) { + return set.title === doctype; + }); + } + + function make_description(content, doc_name) { + var parts = content.split(" ||| "); + var result_max_length = 300; + var field_length = 120; + var fields = []; + var result_current_length = 0; + var field_text = ""; + for(var i = 0; i < parts.length; i++) { + var part = parts[i]; + if(part.toLowerCase().indexOf(keywords) !== -1) { + // If the field contains the keyword + if(part.indexOf(' &&& ') !== -1) { + var colon_index = part.indexOf(' &&& '); + var field_value = part.slice(colon_index + 5); + } else { + var colon_index = part.indexOf(' : '); + var field_value = part.slice(colon_index + 3); + } + if(field_value.length > field_length) { + // If field value exceeds field_length, find the keyword in it + // and trim field value by half the field_length at both sides + // ellipsify if necessary + var field_data = ""; + var index = field_value.indexOf(keywords); + field_data += index < field_length/2 ? field_value.slice(0, index) + : '...' + field_value.slice(index - field_length/2, index) + field_data += field_value.slice(index, index + field_length/2); + field_data += index + field_length/2 < field_value.length ? "..." : ""; + field_value = field_data; + } + var field_name = part.slice(0, colon_index); + + // Find remaining result_length and add field length to result_current_length + var remaining_length = result_max_length - result_current_length; + result_current_length += field_name.length + field_value.length + 2; + if(result_current_length < result_max_length) { + // We have room, push the entire field + field_text = '' + + me.bolden_match_part(field_name, keywords) + ': ' + + me.bolden_match_part(field_value, keywords); + if(fields.indexOf(field_text) === -1 && doc_name !== field_value) { + fields.push(field_text); + } + } else { + // Not enough room + if(field_name.length < remaining_length){ + // Ellipsify (trim at word end) and push + remaining_length -= field_name.length; + field_text = '' + + me.bolden_match_part(field_name, keywords) + ': '; + field_value = field_value.slice(0, remaining_length); + field_value = field_value.slice(0, field_value.lastIndexOf(' ')) + ' ...'; + field_text += me.bolden_match_part(field_value, keywords); + fields.push(field_text); + } else { + // No room for even the field name, skip + fields.push('...'); + } + break; + } + } + } + return fields.join(', '); + } + + data.forEach(function(d) { + // more properties + result = { + label: d.name, + value: d.name, + description: make_description(d.content, d.name), + route: ['Form', d.doctype, d.name], + } + if(d.image || d.image === null){ + result.image = d.image; + } + set = get_existing_set(d.doctype); + if(set) { + set.results.push(result); + } else { + set = { + title: d.doctype, + results: [result], + fetch_type: "Global" + } + results_sets.push(set); + } + + }); + return results_sets; + } + return new Promise(function(resolve, reject) { + frappe.call({ + method: "frappe.utils.global_search.search", + args: { + text: keywords, + start: start, + limit: limit, + doctype: doctype + }, + callback: function(r) { + if(r.message) { + resolve(get_results_sets(r.message)); + } else { + resolve([]); + } + } + }); + }); + }, + + get_help_results: function(keywords) { + function get_results_set(data) { + var result; + var set = { + title: "Help", + fetch_type: "Help", + results: [] + } + data.forEach(function(d) { + // more properties + result = { + label: d[0], + value: d[0], + description: d[1], + data_path: d[2], + onclick: function() { + + } + } + set.results.push(result); + }); + return [set]; + } + return new Promise(function(resolve, reject) { + frappe.call({ + method: "frappe.utils.help.get_help", + args: { + text: keywords + }, + callback: function(r) { + if(r.message) { + resolve(get_results_set(r.message)); + } else { + resolve([]); + } + } + }); + }); + }, + + get_nav_results: function(keywords) { + function sort_uniques(array) { + var routes = [], out = []; + array.forEach(function(d) { + if(d.route) { + if(d.route[0] === "List" && d.route[2]) { + d.route.splice(2); + } + var str_route = d.route.join('/'); + if(routes.indexOf(str_route) === -1) { + routes.push(str_route); + out.push(d); + } else { + var old = routes.indexOf(str_route); + if(out[old].index > d.index) { + out[old] = d; + } + } + } else { + out.push(d); + } + }); + return out.sort(function(a, b) { + return b.index - a.index; + }); + } + var lists = [], setup = []; var all_doctypes = sort_uniques(this.get_doctypes(keywords)); all_doctypes.forEach(function(d) { if(d.type === "") { @@ -464,37 +464,37 @@ frappe.search.utils = { lists.push(d); } }); - var in_keyword = keywords.split(" in ")[0]; + var in_keyword = keywords.split(" in ")[0]; return [ - {title: "Recents", fetch_type: "Nav", results: sort_uniques(this.get_recent_pages(keywords))}, - {title: "Create a new ...", fetch_type: "Nav", results: sort_uniques(this.get_creatables(keywords))}, - {title: "Find '" + in_keyword + "' in ... ", fetch_type: "Nav", results: sort_uniques(this.get_search_in_list(keywords))}, - {title: "Lists", fetch_type: "Nav", results: lists}, + {title: "Recents", fetch_type: "Nav", results: sort_uniques(this.get_recent_pages(keywords))}, + {title: "Create a new ...", fetch_type: "Nav", results: sort_uniques(this.get_creatables(keywords))}, + {title: "Find '" + in_keyword + "' in ... ", fetch_type: "Nav", results: sort_uniques(this.get_search_in_list(keywords))}, + {title: "Lists", fetch_type: "Nav", results: lists}, {title: "Reports", fetch_type: "Nav", results: sort_uniques(this.get_reports(keywords))}, - {title: "Administration", fetch_type: "Nav", results: sort_uniques(this.get_pages(keywords))}, + {title: "Administration", fetch_type: "Nav", results: sort_uniques(this.get_pages(keywords))}, {title: "Modules", fetch_type: "Nav", results: sort_uniques(this.get_modules(keywords))}, - {title: "Setup", fetch_type: "Nav", results: setup}, - ] - }, + {title: "Setup", fetch_type: "Nav", results: setup}, + ] + }, - fuzzy_search: function(keywords, _item) { - // Returns 10 for case-perfect contain, 0 for not found - // 9 for perfect contain, - // 0 - 6 for fuzzy contain + fuzzy_search: function(keywords, _item) { + // Returns 10 for case-perfect contain, 0 for not found + // 9 for perfect contain, + // 0 - 6 for fuzzy contain - // **Specific use-case step** - item = __(_item || '').replace(/-/g, " "); + // **Specific use-case step** + var item = __(_item || '').replace(/-/g, " "); var ilen = item.length; var klen = keywords.length; - var length_ratio = klen/ilen; - var max_skips = 3, max_mismatch_len = 2; + var length_ratio = klen/ilen; + var max_skips = 3, max_mismatch_len = 2; if (klen > ilen) { return 0; } - if(keywords === item || item.toLowerCase().indexOf(keywords) === 0) { - return 10 + length_ratio; - } + if(keywords === item || item.toLowerCase().indexOf(keywords) === 0) { + return 10 + length_ratio; + } if (item.indexOf(keywords) !== -1 && keywords !== keywords.toLowerCase()) { return 9 + length_ratio; @@ -507,11 +507,11 @@ frappe.search.utils = { return 8 + length_ratio; } - var skips = 0, mismatches = 0; + var skips = 0, mismatches = 0; outer: for (var i = 0, j = 0; i < klen; i++) { if(mismatches !== 0) skips++; if(skips > max_skips) return 0; - var k_ch = keywords.charCodeAt(i); + var k_ch = keywords.charCodeAt(i); mismatches = 0; while (j < ilen) { if (item.charCodeAt(j++) === k_ch) { @@ -522,49 +522,49 @@ frappe.search.utils = { return 0; } - // Since indexOf didn't pass, there will be atleast 1 skip - // hence no divide by zero, but just to be safe - if((skips + mismatches) > 0) { - return (5 + length_ratio)/(skips + mismatches); - } else { - return 0; - } + // Since indexOf didn't pass, there will be atleast 1 skip + // hence no divide by zero, but just to be safe + if((skips + mismatches) > 0) { + return (5 + length_ratio)/(skips + mismatches); + } else { + return 0; + } }, - bolden_match_part: function(str, subseq) { + bolden_match_part: function(str, subseq) { var rendered = ""; - if(this.fuzzy_search(subseq, str) === 0) { - return str; - } else if(this.fuzzy_search(subseq, str) > 6) { - var regEx = new RegExp("("+ subseq +")", "ig"); - return str.replace(regEx, '$1'); - } else { - var str_orig = str; - var str = str.toLowerCase(); - var str_len = str.length; - var subseq = subseq.toLowerCase(); - - outer: for(var i = 0, j = 0; i < subseq.length; i++) { - var sub_ch = subseq.charCodeAt(i); - while(j < str_len) { - if(str.charCodeAt(j) === sub_ch) { - var str_char = str_orig.charAt(j); - if(str_char === str_char.toLowerCase()) { - rendered += '' + subseq.charAt(i) + ''; - } else { - rendered += '' + subseq.charAt(i).toUpperCase() + ''; - } - j++; - continue outer; - } - rendered += str_orig.charAt(j); - j++; - } - return str_orig; - } - rendered += str_orig.slice(j); - return rendered; - } - - }, + if(this.fuzzy_search(subseq, str) === 0) { + return str; + } else if(this.fuzzy_search(subseq, str) > 6) { + var regEx = new RegExp("("+ subseq +")", "ig"); + return str.replace(regEx, '$1'); + } else { + var str_orig = str; + var str = str.toLowerCase(); + var str_len = str.length; + var subseq = subseq.toLowerCase(); + + outer: for(var i = 0, j = 0; i < subseq.length; i++) { + var sub_ch = subseq.charCodeAt(i); + while(j < str_len) { + if(str.charCodeAt(j) === sub_ch) { + var str_char = str_orig.charAt(j); + if(str_char === str_char.toLowerCase()) { + rendered += '' + subseq.charAt(i) + ''; + } else { + rendered += '' + subseq.charAt(i).toUpperCase() + ''; + } + j++; + continue outer; + } + rendered += str_orig.charAt(j); + j++; + } + return str_orig; + } + rendered += str_orig.slice(j); + return rendered; + } + + }, } diff --git a/frappe/public/js/frappe/ui/toolbar/toolbar.js b/frappe/public/js/frappe/ui/toolbar/toolbar.js index 70ef6b71af..24fe005afb 100644 --- a/frappe/public/js/frappe/ui/toolbar/toolbar.js +++ b/frappe/public/js/frappe/ui/toolbar/toolbar.js @@ -162,7 +162,7 @@ frappe.ui.toolbar.Toolbar = Class.extend({ function show_results(e) { //edit links - href = e.target.href; + var href = e.target.href; if(href.indexOf('blob') > 0) { window.open(href, '_blank'); } @@ -220,7 +220,7 @@ frappe.ui.toolbar.clear_cache = function() { frappe.assets.clear_local_storage(); $c('frappe.sessions.clear',{},function(r,rt){ if(!r.exc) { - show_alert(r.message); + frappe.show_alert(r.message); location.reload(true); } }); @@ -228,7 +228,7 @@ frappe.ui.toolbar.clear_cache = function() { } frappe.ui.toolbar.download_backup = function() { - msgprint(__("Your download is being built, this may take a few moments...")); + frappe.msgprint(__("Your download is being built, this may take a few moments...")); $c('frappe.utils.backups.get_backup',{},function(r,rt) {}); return false; } diff --git a/frappe/public/js/frappe/ui/tree.js b/frappe/public/js/frappe/ui/tree.js index 0e6455606a..33e57ae3d9 100644 --- a/frappe/public/js/frappe/ui/tree.js +++ b/frappe/public/js/frappe/ui/tree.js @@ -231,7 +231,7 @@ frappe.ui.TreeNode = Class.extend({ }, load: function(callback) { var node = this; - args = $.extend(this.tree.args || {}, { + var args = $.extend(this.tree.args || {}, { parent: this.data.value }); diff --git a/frappe/public/js/frappe/upload.js b/frappe/public/js/frappe/upload.js index b80b3b21d5..61540cd648 100644 --- a/frappe/public/js/frappe/upload.js +++ b/frappe/public/js/frappe/upload.js @@ -219,7 +219,7 @@ frappe.upload = { if(opts.on_no_attach) { opts.on_no_attach(); } else { - msgprint(__("Please attach a file or set a URL")); + frappe.msgprint(__("Please attach a file or set a URL")); } return; } @@ -267,21 +267,21 @@ frappe.upload = { args.filename = fileobj.name.split(' ').join('_'); if(opts.options && opts.options.toLowerCase()=="image") { if(!frappe.utils.is_image_file(args.filename)) { - msgprint(__("Only image extensions (.gif, .jpg, .jpeg, .tiff, .png, .svg) allowed")); + frappe.msgprint(__("Only image extensions (.gif, .jpg, .jpeg, .tiff, .png, .svg) allowed")); return; } } if((opts.max_width || opts.max_height) && frappe.utils.is_image_file(args.filename)) { frappe.utils.resize_image(freader, function(_dataurl) { - dataurl = _dataurl; + var dataurl = _dataurl; args.filedata = _dataurl.split(",")[1]; args.file_size = Math.round(args.filedata.length * 3 / 4); console.log("resized!") frappe.upload._upload_file(fileobj, args, opts, dataurl); }) } else { - dataurl = freader.result; + var dataurl = freader.result; args.filedata = freader.result.split(",")[1]; args.file_size = fileobj.size; frappe.upload._upload_file(fileobj, args, opts, dataurl); @@ -292,11 +292,11 @@ frappe.upload = { }, upload_to_server: function(fileobj, args, opts, dataurl) { - // var msgbox = msgprint(__("Uploading...")); + // var msgbox = frappe.msgprint(__("Uploading...")); if(opts.start) { opts.start(); } - ajax_args = { + var ajax_args = { "method": "uploadfile", args: args, callback: function(r) { @@ -357,26 +357,26 @@ frappe.upload = { var filename = fileobjs[i].name; fields.push({'fieldname': 'label1', 'fieldtype': 'Heading', 'label': filename}); fields.push({'fieldname': filename+'_is_private', 'fieldtype': 'Check', 'label': 'Private', 'default': 1}); - } + } - var d = new frappe.ui.Dialog({ - 'title': __('Make file(s) private or public?'), - 'fields': fields, - primary_action: function(){ - var i =0,j = fileobjs.length; - d.hide(); - opts.loopcallback = function (){ - if (i < j) { - args.is_private = d.fields_dict[fileobjs[i].name + "_is_private"].get_value() - frappe.upload.upload_file(fileobjs[i], args, opts); - i++; - } + var d = new frappe.ui.Dialog({ + 'title': __('Make file(s) private or public?'), + 'fields': fields, + primary_action: function(){ + var i =0,j = fileobjs.length; + d.hide(); + opts.loopcallback = function (){ + if (i < j) { + args.is_private = d.fields_dict[fileobjs[i].name + "_is_private"].get_value() + frappe.upload.upload_file(fileobjs[i], args, opts); + i++; } - - opts.loopcallback(); } - }); - d.show(); - opts.confirm_is_private = 0; + + opts.loopcallback(); + } + }); + d.show(); + opts.confirm_is_private = 0; } } \ No newline at end of file diff --git a/frappe/public/js/frappe/views/calendar/calendar.js b/frappe/public/js/frappe/views/calendar/calendar.js index 6c5fdff43d..2212870480 100644 --- a/frappe/public/js/frappe/views/calendar/calendar.js +++ b/frappe/public/js/frappe/views/calendar/calendar.js @@ -264,7 +264,7 @@ frappe.views.Calendar = Class.extend({ args: me.get_update_args(event), callback: function(r) { if(r.exc) { - show_alert(__("Unable to update event")); + frappe.show_alert(__("Unable to update event")); revertFunc(); } }, @@ -325,7 +325,7 @@ frappe.views.Calendar = Class.extend({ $.each(this.filters, function(i, df) { if(df.options===value) me.page.fields_dict[df.fieldname].set_input(value); - return false; + return false; }); } }, @@ -346,7 +346,7 @@ frappe.views.Calendar = Class.extend({ $.each(frappe.route_options, function(k, value) { if(me.page.fields_dict[k]) { me.page.fields_dict[k].set_input(value); - }; + } }) frappe.route_options = null; me.refresh(); diff --git a/frappe/public/js/frappe/views/communication.js b/frappe/public/js/frappe/views/communication.js index 6f00823481..f2475d83fd 100755 --- a/frappe/public/js/frappe/views/communication.js +++ b/frappe/public/js/frappe/views/communication.js @@ -85,8 +85,8 @@ frappe.views.CommunicationComposer = Class.extend({ ]; // add from if user has access to multiple email accounts - email_accounts = frappe.boot.email_accounts.filter(function(account, idx){ - return !inList(["All Accounts", "Sent", "Spam", "Trash"], account.email_account) && + var email_accounts = frappe.boot.email_accounts.filter(function(account, idx){ + return !in_list(["All Accounts", "Sent", "Spam", "Trash"], account.email_account) && account.enable_outgoing }) if(frappe.boot.email_accounts && email_accounts.length > 1) { @@ -168,7 +168,7 @@ frappe.views.CommunicationComposer = Class.extend({ var content = content_field.get_value() || ""; var subject = subject_field.get_value() || ""; - parts = content.split(''); + var parts = content.split(''); if(parts.length===2) { content = [reply.message, " '+__("Calculate")+' '+ __("e.g. (55 + 434) / 4 or =Math.sin(Math.PI/2)...")+'
", parts[1]]; @@ -318,8 +318,8 @@ frappe.views.CommunicationComposer = Class.extend({ if(me.frm) { args = { args: (me.frm.attachments.get_args - ? me.frm.attachments.get_args() - : { from_form: 1,folder:"Home/Attachments" }), + ? me.frm.attachments.get_args() + : { from_form: 1,folder:"Home/Attachments" }), callback: function (attachment, r) { me.frm.attachments.attachment_uploaded(attachment, r) }, @@ -334,7 +334,7 @@ frappe.views.CommunicationComposer = Class.extend({ ").appendTo(attach.empty()) - attach.find(".add-more-attachments a").on('click',this,function() { + attach.find(".add-more-attachments a").on('click',this,function() { me.upload = frappe.ui.get_upload_dialog(args); }) me.render_attach() @@ -397,10 +397,12 @@ frappe.views.CommunicationComposer = Class.extend({ var form_values = this.get_values(); if(!form_values) return; - var selected_attachments = $.map($(me.dialog.wrapper) - .find("[data-file-name]:checked"), function(element) { + var selected_attachments = + $.map($(me.dialog.wrapper) + .find("[data-file-name]:checked"), function (element) { return $(element).attr("data-file-name"); - }) + }); + if(form_values.attach_document_print) { if (cur_frm.print_preview.is_old_style(form_values.select_print_format || "")) { @@ -442,10 +444,10 @@ frappe.views.CommunicationComposer = Class.extend({ send_email: function(btn, form_values, selected_attachments, print_html, print_format) { var me = this; - if((form_values.send_email || form_values.communication_medium === "Email") && !form_values.recipients){ - msgprint(__("Enter Email Recipient(s)")); - return; - } + if((form_values.send_email || form_values.communication_medium === "Email") && !form_values.recipients) { + frappe.msgprint(__("Enter Email Recipient(s)")); + return; + } if(!form_values.attach_document_print) { print_html = null; @@ -454,13 +456,13 @@ frappe.views.CommunicationComposer = Class.extend({ if(form_values.send_email) { if(cur_frm && !frappe.model.can_email(me.doc.doctype, cur_frm)) { - msgprint(__("You are not allowed to send emails related to this document")); + frappe.msgprint(__("You are not allowed to send emails related to this document")); return; } form_values.communication_medium = "Email"; form_values.sent_or_received = "Sent"; - }; + } return frappe.call({ method:"frappe.core.doctype.communication.email.make", @@ -489,14 +491,14 @@ frappe.views.CommunicationComposer = Class.extend({ frappe.utils.play_sound("email"); if(form_values.send_email && r.message["emails_not_sent_to"]) { - msgprint( __("Email not sent to {0} (unsubscribed / disabled)", + frappe.msgprint(__("Email not sent to {0} (unsubscribed / disabled)", [ frappe.utils.escape_html(r.message["emails_not_sent_to"]) ]) ); } me.dialog.hide(); if ((frappe.last_edited_communication[me.doc] || {})[me.key]) { - delete frappe.last_edited_communication[me.doc][me.key]; + delete frappe.last_edited_communication[me.doc][me.key]; } if (cur_frm) { // clear input @@ -504,7 +506,7 @@ frappe.views.CommunicationComposer = Class.extend({ cur_frm.reload_doc(); } } else { - msgprint(__("There were errors while sending email. Please try again.")); + frappe.msgprint(__("There were errors while sending email. Please try again.")); } } }); @@ -553,11 +555,12 @@ frappe.views.CommunicationComposer = Class.extend({ }, setup_awesomplete: function() { var me = this; - [this.dialog.fields_dict.recipients.input, - this.dialog.fields_dict.cc.input] - .map(function(input) { - me.setup_awesomplete_for_input(input); - }); + [ + this.dialog.fields_dict.recipients.input, + this.dialog.fields_dict.cc.input + ].map(function(input) { + me.setup_awesomplete_for_input(input); + }); }, setup_awesomplete_for_input: function(input) { function split(val) { diff --git a/frappe/public/js/frappe/views/gantt/gantt_view.js b/frappe/public/js/frappe/views/gantt/gantt_view.js index 704a5a26a2..b83acd241f 100644 --- a/frappe/public/js/frappe/views/gantt/gantt_view.js +++ b/frappe/public/js/frappe/views/gantt/gantt_view.js @@ -181,7 +181,7 @@ frappe.views.GanttView = frappe.views.ListRenderer.extend({ }, callback: function() { me.gantt.updating_task = false; - show_alert({message:__("Saved"), indicator: 'green'}, 1); + frappe.show_alert({message:__("Saved"), indicator: 'green'}, 1); } }); }, @@ -198,7 +198,7 @@ frappe.views.GanttView = frappe.views.ListRenderer.extend({ } else { // reset gantt state this.gantt.change_view_mode(this.gantt_view_mode); - show_alert({message: __("Not permitted"), indicator: 'red'}, 1); + frappe.show_alert({message: __("Not permitted"), indicator: 'red'}, 1); return false; } }, diff --git a/frappe/public/js/frappe/views/image/image_view.js b/frappe/public/js/frappe/views/image/image_view.js index b35fd04456..9113ff146f 100644 --- a/frappe/public/js/frappe/views/image/image_view.js +++ b/frappe/public/js/frappe/views/image/image_view.js @@ -169,7 +169,7 @@ frappe.views.GalleryView = Class.extend({ freeze_message: "Fetching Images.." }).then(function(r) { if (!r.message) { - msgprint("No Images found") + frappe.msgprint("No Images found") } else { // filter image files from other var images = r.message.filter(function(image) { diff --git a/frappe/public/js/frappe/views/inbox/inbox_view.js b/frappe/public/js/frappe/views/inbox/inbox_view.js index 15a8af013f..a028860c73 100644 --- a/frappe/public/js/frappe/views/inbox/inbox_view.js +++ b/frappe/public/js/frappe/views/inbox/inbox_view.js @@ -2,7 +2,7 @@ * frappe.views.EmailInboxView */ - frappe.provide("frappe.views"); +frappe.provide("frappe.views"); frappe.views.InboxView = frappe.views.ListRenderer.extend({ name: 'Inbox', @@ -20,7 +20,7 @@ frappe.views.InboxView = frappe.views.ListRenderer.extend({ render_inbox_view: function() { var html = "" - email_account = this.get_current_email_account() + var email_account = this.get_current_email_account() if(email_account) html = this.emails.map(this.render_email_row.bind(this)).join(""); else @@ -78,7 +78,7 @@ frappe.views.InboxView = frappe.views.ListRenderer.extend({ ["Communication", "email_status", "not in", "Spam,Trash", true], ]) } - else if (inList(["Spam", "Trash"], email_account)) { + else if (in_list(["Spam", "Trash"], email_account)) { filters = default_filters.concat([ ["Communication", "email_status", "=", email_account, true], ["Communication", "email_account", "in", frappe.boot.all_accounts, true] @@ -115,6 +115,7 @@ frappe.views.InboxView = frappe.views.ListRenderer.extend({ get_current_email_account: function() { var route = frappe.get_route(); if(!route[3] && frappe.boot.email_accounts.length) { + var email_account; if(frappe.boot.email_accounts[0].email_id == "All Accounts") { email_account = "All Accounts" } else { @@ -130,8 +131,9 @@ frappe.views.InboxView = frappe.views.ListRenderer.extend({ }, make_no_result: function () { var no_result_message = "" - email_account = this.get_current_email_account(); - if (inList(["Spam", "Trash"], email_account)) { + var email_account = this.get_current_email_account(); + var args; + if (in_list(["Spam", "Trash"], email_account)) { return __("No {0} mail", [email_account]) } else if(!email_account && !frappe.boot.email_accounts.length) { // email account is not configured @@ -159,7 +161,7 @@ frappe.views.InboxView = frappe.views.ListRenderer.extend({ doc: {} }) } else { - frappe.route_options = { 'email_id': user_email } + frappe.route_options = { 'email_id': frappe.session.user_email } frappe.new_doc(this.no_result_doctype) } } diff --git a/frappe/public/js/frappe/views/kanban/kanban_board.js b/frappe/public/js/frappe/views/kanban/kanban_board.js index 1450aca7b1..097df1b811 100644 --- a/frappe/public/js/frappe/views/kanban/kanban_board.js +++ b/frappe/public/js/frappe/views/kanban/kanban_board.js @@ -119,7 +119,7 @@ frappe.provide("frappe.views"); }).then(function(r) { saving_filters = false; updater.set({ filters_modified: false }); - show_alert({ + frappe.show_alert({ message: __('Filters saved'), indicator: 'green' }, 0.5); @@ -819,37 +819,6 @@ frappe.provide("frappe.views"); }) } - function edit_card_title_old() { - - self.$card.find('.kanban-card-edit').on('click', function (e) { - e.stopPropagation(); - $edit_card_area.show(); - $kanban_card_area.hide(); - $textarea.focus(); - }); - - $textarea.on('blur', function () { - $edit_card_area.hide(); - $kanban_card_area.show(); - }); - - $textarea.keydown(function (e) { - if (e.which === 13) { - e.preventDefault(); - var new_title = $textarea.val(); - if (card.title === new_title) { - return; - } - get_doc().then(function () { - var tf = store.getState().card_meta.title_field.fieldname; - var doc = card.doc; - doc[tf] = new_title; - fluxify.doAction('update_doc', doc, card); - }) - } - }) - } - init(); } @@ -1020,7 +989,7 @@ frappe.provide("frappe.views"); }, callback: function (r) { frappe.model.clear_doc(doc.doctype, doc.name); - show_alert({ message: __("Saved"), indicator: 'green' }, 1); + frappe.show_alert({ message: __("Saved"), indicator: 'green' }, 1); } }); } diff --git a/frappe/public/js/frappe/views/kanban/kanban_view.js b/frappe/public/js/frappe/views/kanban/kanban_view.js index 5590f689be..5703282254 100644 --- a/frappe/public/js/frappe/views/kanban/kanban_view.js +++ b/frappe/public/js/frappe/views/kanban/kanban_view.js @@ -71,7 +71,7 @@ frappe.views.KanbanView = frappe.views.ListRenderer.extend({ return frappe.render_template('list_item_row_head', { main: '', list: this }); }, required_libs: [ - 'assets/frappe/js/frappe/views/kanban/fluxify.min.js', + 'assets/frappe/js/lib/fluxify.min.js', 'assets/frappe/js/frappe/views/kanban/kanban_board.js' ] }); \ No newline at end of file diff --git a/frappe/public/js/frappe/views/pageview.js b/frappe/public/js/frappe/views/pageview.js index e763c2cc97..7f3f42b4ce 100644 --- a/frappe/public/js/frappe/views/pageview.js +++ b/frappe/public/js/frappe/views/pageview.js @@ -6,7 +6,7 @@ frappe.provide("frappe.standard_pages"); frappe.views.pageview = { with_page: function(name, callback) { - if(in_list(keys(frappe.standard_pages), name)) { + if(in_list(Object.keys(frappe.standard_pages), name)) { if(!frappe.pages[name]) { frappe.standard_pages[name](); } diff --git a/frappe/public/js/frappe/views/reports/grid_report.js b/frappe/public/js/frappe/views/reports/grid_report.js index 9e7f7ad2c0..96a4e6182e 100644 --- a/frappe/public/js/frappe/views/reports/grid_report.js +++ b/frappe/public/js/frappe/views/reports/grid_report.js @@ -7,7 +7,7 @@ $.extend(frappe.report_dump, { data: {}, last_modified: {}, with_data: function(doctypes, callback) { - var pre_loaded = keys(frappe.report_dump.last_modified); + var pre_loaded = Object.keys(frappe.report_dump.last_modified); return frappe.call({ method: "frappe.desk.report_dump.get_data", type: "GET", @@ -148,10 +148,10 @@ frappe.views.GridReport = Class.extend({ var me = this; $.each(me.filter_inputs, function(i, v) { var opts = v.get(0).opts; - if(opts.fieldtype == "Select" && inList(me.doctypes, opts.link)) { + if(opts.fieldtype == "Select" && in_list(me.doctypes, opts.link)) { $(v).add_options($.map(frappe.report_dump.data[opts.link], function(d) { return d.name; })); - } else if(opts.fieldtype == "Link" && inList(me.doctypes, opts.link)) { + } else if(opts.fieldtype == "Link" && in_list(me.doctypes, opts.link)) { opts.list = $.map(frappe.report_dump.data[opts.link], function(d) { return d.name; }); me.set_autocomplete(v, opts.list); @@ -201,7 +201,7 @@ frappe.views.GridReport = Class.extend({ filters.val(value); } } else { - msgprint(__("Invalid Filter: {0}", [key])) + frappe.msgprint(__("Invalid Filter: {0}", [key])) } }, set_autocomplete: function($filter, list) { @@ -219,8 +219,8 @@ frappe.views.GridReport = Class.extend({ var me = this; $.each(this.filter_inputs, function(key, filter) { var opts = filter.get(0).opts; - if(sys_defaults[key]) { - filter.val(sys_defaults[key]); + if(frappe.sys_defaults[key]) { + filter.val(frappe.sys_defaults[key]); } else if(opts.fieldtype=='Select') { filter.get(0).selectedIndex = 0; } else if(opts.fieldtype=='Data') { @@ -235,8 +235,8 @@ frappe.views.GridReport = Class.extend({ set_default_values: function() { var values = { - from_date: dateutil.str_to_user(sys_defaults.year_start_date), - to_date: dateutil.str_to_user(sys_defaults.year_end_date) + from_date: frappe.datetime.str_to_user(frappe.sys_defaults.year_start_date), + to_date: frappe.datetime.str_to_user(frappe.sys_defaults.year_end_date) } var me = this; @@ -298,7 +298,7 @@ frappe.views.GridReport = Class.extend({ } else if(opts.fieldtype!='Button') { me[opts.fieldname] = f.val(); if(opts.fieldtype=="Date") { - me[opts.fieldname] = dateutil.user_to_str(me[opts.fieldname]); + me[opts.fieldname] = frappe.datetime.user_to_str(me[opts.fieldname]); } else if (opts.fieldtype == "Select") { me[opts.fieldname+'_default'] = opts.default_value; } @@ -306,7 +306,7 @@ frappe.views.GridReport = Class.extend({ }); if(this.filter_inputs.from_date && this.filter_inputs.to_date && (this.to_date < this.from_date)) { - msgprint(__("From Date must be before To Date")); + frappe.msgprint(__("From Date must be before To Date")); return; } @@ -359,7 +359,7 @@ frappe.views.GridReport = Class.extend({ this.round_off_data(); this.prepare_data_view(); // chart might need prepared data - show_alert("Updated", 2); + frappe.show_alert("Updated", 2); this.render(); this.setup_chart && this.setup_chart(); }, @@ -458,7 +458,7 @@ frappe.views.GridReport = Class.extend({ var filters = this.filter_inputs; if(item._show) return true; - for (i in filters) { + for (var i in filters) { if(!this.apply_filter(item, i)) { return false; } @@ -502,7 +502,7 @@ frappe.views.GridReport = Class.extend({ return this[fieldname]==this[fieldname + "_default"]; }, date_formatter: function(row, cell, value, columnDef, dataContext) { - return dateutil.str_to_user(value); + return frappe.datetime.str_to_user(value); }, currency_formatter: function(row, cell, value, columnDef, dataContext) { return repl('%(value)s', { @@ -577,18 +577,18 @@ frappe.views.GridReport = Class.extend({ get_link_open_icon: function(doctype, name) { return repl(' \ ', { - doctype: doctype, - name: encodeURIComponent(name) - }); + doctype: doctype, + name: encodeURIComponent(name) + }); }, make_date_range_columns: function() { this.columns = []; var me = this; var range = this.filter_inputs.range.val(); - this.from_date = dateutil.user_to_str(this.filter_inputs.from_date.val()); - this.to_date = dateutil.user_to_str(this.filter_inputs.to_date.val()); - var date_diff = dateutil.get_diff(this.to_date, this.from_date); + this.from_date = frappe.datetime.user_to_str(this.filter_inputs.from_date.val()); + this.to_date = frappe.datetime.user_to_str(this.filter_inputs.to_date.val()); + var date_diff = frappe.datetime.get_diff(this.to_date, this.from_date); me.column_map = {}; me.last_date = null; @@ -596,7 +596,7 @@ frappe.views.GridReport = Class.extend({ var add_column = function(date) { me.columns.push({ id: date, - name: dateutil.str_to_user(date), + name: frappe.datetime.str_to_user(date), field: date, formatter: me.currency_formatter, width: 100 @@ -606,7 +606,7 @@ frappe.views.GridReport = Class.extend({ var build_columns = function(condition) { // add column for each date range for(var i=0; i <= date_diff; i++) { - var date = dateutil.add_days(me.from_date, i); + var date = frappe.datetime.add_days(me.from_date, i); if(!condition) condition = function() { return true; } if(condition(date)) add_column(date); @@ -624,24 +624,24 @@ frappe.views.GridReport = Class.extend({ } else if(range=='Weekly') { build_columns(function(date) { if(!me.last_date) return true; - return !(dateutil.get_diff(date, me.from_date) % 7) + return !(frappe.datetime.get_diff(date, me.from_date) % 7) }); } else if(range=='Monthly') { build_columns(function(date) { if(!me.last_date) return true; - return dateutil.str_to_obj(me.last_date).getMonth() != dateutil.str_to_obj(date).getMonth() + return frappe.datetime.str_to_obj(me.last_date).getMonth() != frappe.datetime.str_to_obj(date).getMonth() }); } else if(range=='Quarterly') { build_columns(function(date) { if(!me.last_date) return true; - return dateutil.str_to_obj(date).getDate()==1 && in_list([0,3,6,9], dateutil.str_to_obj(date).getMonth()) + return frappe.datetime.str_to_obj(date).getDate()==1 && in_list([0,3,6,9], frappe.datetime.str_to_obj(date).getMonth()) }); } else if(range=='Yearly') { build_columns(function(date) { if(!me.last_date) return true; return $.map(frappe.report_dump.data['Fiscal Year'], function(v) { - return date==v.year_start_date ? true : null; - }).length; + return date==v.year_start_date ? true : null; + }).length; }); } @@ -649,8 +649,8 @@ frappe.views.GridReport = Class.extend({ // set label as last date of period $.each(this.columns, function(i, col) { col.name = me.columns[i+1] - ? dateutil.str_to_user(dateutil.add_days(me.columns[i+1].id, -1)) - : dateutil.str_to_user(me.to_date); + ? frappe.datetime.str_to_user(frappe.datetime.add_days(me.columns[i+1].id, -1)) + : frappe.datetime.str_to_user(me.to_date); }); }, trigger_refresh_on_change: function(filters) { @@ -815,7 +815,7 @@ frappe.views.TreeGridReport = frappe.views.GridReportWithPlot.extend({ if(group_ids.indexOf(item.name)==-1) { item_group_map[parent].push(item); } else { - msgprint(__("Ignoring Item {0}, because a group exists with the same name!", [item.name.bold()])); + frappe.msgprint(__("Ignoring Item {0}, because a group exists with the same name!", [item.name.bold()])); } }); @@ -844,7 +844,7 @@ frappe.views.TreeGridReport = frappe.views.GridReportWithPlot.extend({ }, export: function() { - var msgbox = msgprint($.format('{0}
\ + var msgbox = frappe.msgprint($.format('{0}
\{1}
\{2}
\', [ @@ -874,7 +874,7 @@ frappe.views.TreeGridReport = frappe.views.GridReportWithPlot.extend({ } return false; - }); + }); frappe.tools.downloadify(data, ["Report Manager", "System Manager"], me.title); return false; diff --git a/frappe/public/js/frappe/views/reports/query_report.js b/frappe/public/js/frappe/views/reports/query_report.js index 5277aaef15..f323c91afd 100644 --- a/frappe/public/js/frappe/views/reports/query_report.js +++ b/frappe/public/js/frappe/views/reports/query_report.js @@ -33,10 +33,10 @@ frappe.views.QueryReport = Class.extend({ }, slickgrid_options: { enableColumnReorder: false, - showHeaderRow: true, - headerRowHeight: 30, - explicitInitialization: true, - multiColumnSort: true + showHeaderRow: true, + headerRowHeight: 30, + explicitInitialization: true, + multiColumnSort: true }, make: function() { var me = this; @@ -69,7 +69,7 @@ frappe.views.QueryReport = Class.extend({ // Edit this.page.add_menu_item(__('Edit'), function() { if(!frappe.user.is_report_manager()) { - msgprint(__("You are not allowed to create / edit reports")); + frappe.msgprint(__("You are not allowed to create / edit reports")); return false; } frappe.set_route("Form", "Report", me.report_name); @@ -181,7 +181,7 @@ frappe.views.QueryReport = Class.extend({ }, print_report: function() { if(!frappe.model.can_print(this.report_doc.ref_doctype)) { - msgprint(__("You are not allowed to print this report")); + frappe.msgprint(__("You are not allowed to print this report")); return false; } @@ -211,7 +211,7 @@ frappe.views.QueryReport = Class.extend({ var print_css = frappe.boot.print_css; if(!frappe.model.can_print(this.report_doc.ref_doctype)) { - msgprint(__("You are not allowed to make PDF for this report")); + frappe.msgprint(__("You are not allowed to make PDF for this report")); return false; } @@ -222,14 +222,14 @@ frappe.views.QueryReport = Class.extend({ {data: frappe.slickgrid_tools.get_filtered_items(this.dataView), filters:this.get_values(), report:this}); //Render Report in HTML - var html = frappe.render_template("print_template", { - content:content, - title:__(this.report_name), - base_url: base_url, - print_css: print_css, - print_settings: this.print_settings, - landscape: landscape - }); + var html = frappe.render_template("print_template", { + content:content, + title:__(this.report_name), + base_url: base_url, + print_css: print_css, + print_settings: this.print_settings, + landscape: landscape + }); } else { // rows filtered by inline_filter of slickgrid var visible_idx = frappe.slickgrid_tools @@ -277,13 +277,13 @@ frappe.views.QueryReport = Class.extend({ xhr.responseType = "arraybuffer"; xhr.onload = function(success) { - if (this.status === 200) { - var blob = new Blob([success.currentTarget.response], {type: "application/pdf"}); - var objectUrl = URL.createObjectURL(blob); + if (this.status === 200) { + var blob = new Blob([success.currentTarget.response], {type: "application/pdf"}); + var objectUrl = URL.createObjectURL(blob); - //Open report in a new window - window.open(objectUrl); - } + //Open report in a new window + window.open(objectUrl); + } }; xhr.send(formData); }, @@ -519,7 +519,7 @@ frappe.views.QueryReport = Class.extend({ col.name = col.id = col.label = df.label; return col - })); + })); }, filter_hidden_columns: function() { this.columns = $.map(this.columns, function(c, i) { @@ -563,7 +563,7 @@ frappe.views.QueryReport = Class.extend({ var newrow = {}; for(var i=1, j=this.columns.length; i
", { - row: row, - checked: (dataContext.selected ? "checked=\"checked\"" : "") - }); - } + formatter: function(row, cell, value, columnDef, dataContext) { + return repl("", { + row: row, + checked: (dataContext.selected ? "checked=\"checked\"" : "") + }); + } }]); } return std_columns.concat(this.build_columns()); @@ -708,7 +708,7 @@ frappe.views.ReportView = frappe.ui.BaseList.extend({ } var export_btn = this.page.add_menu_item(__('Export'), function() { var args = me.get_args(); - selected_items = me.get_checked_items() + var selected_items = me.get_checked_items() frappe.prompt({fieldtype:"Select", label: __("Select File Type"), fieldname:"file_format_type", options:"Excel\nCSV", default:"Excel", reqd: 1}, function(data) { @@ -761,7 +761,7 @@ frappe.views.ReportView = frappe.ui.BaseList.extend({ }, callback: function(r) { if(r.exc) { - msgprint(__("Report was not saved (there were errors)")); + frappe.msgprint(__("Report was not saved (there were errors)")); return; } if(r.message != me.docname) @@ -790,7 +790,7 @@ frappe.views.ReportView = frappe.ui.BaseList.extend({ }); this.page.add_menu_item(__("Delete"), function() { - delete_list = $.map(me.get_checked_items(), function(d) { return d.name; }); + var delete_list = $.map(me.get_checked_items(), function(d) { return d.name; }); if(!delete_list.length) return; if(frappe.confirm(__("This is PERMANENT action and you cannot undo. Continue?"), diff --git a/frappe/public/js/frappe/views/test_runner.js b/frappe/public/js/frappe/views/test_runner.js index 499ea77577..2e8638d9bc 100644 --- a/frappe/public/js/frappe/views/test_runner.js +++ b/frappe/public/js/frappe/views/test_runner.js @@ -14,7 +14,7 @@ frappe.standard_pages["test-runner"] = function() { var route = frappe.get_route(); if(route.length < 2) { - msgprint(__("To run a test add the module name in the route after '{0}'. For example, {1}", ['test-runner/', '#test-runner/lib/js/frappe/test_app.js'])); + frappe.msgprint(__("To run a test add the module name in the route after '{0}'. For example, {1}", ['test-runner/', '#test-runner/lib/js/frappe/test_app.js'])); return; } diff --git a/frappe/public/js/frappe/views/treeview.js b/frappe/public/js/frappe/views/treeview.js index c7acb981b3..ebc10776d2 100644 --- a/frappe/public/js/frappe/views/treeview.js +++ b/frappe/public/js/frappe/views/treeview.js @@ -14,7 +14,7 @@ frappe.views.TreeFactory = frappe.views.Factory.extend({ }; if (!frappe.treeview_settings[route[1]] && !frappe.meta.get_docfield(route[1], "is_group")) { - msgprint(__("Tree view not available for {0}", [route[1]] )); + frappe.msgprint(__("Tree view not available for {0}", [route[1]] )); return false; } $.extend(options, frappe.treeview_settings[route[1]] || {}); diff --git a/frappe/public/js/legacy/clientscriptAPI.js b/frappe/public/js/legacy/clientscriptAPI.js index abca684277..7a4af8222e 100644 --- a/frappe/public/js/legacy/clientscriptAPI.js +++ b/frappe/public/js/legacy/clientscriptAPI.js @@ -1,12 +1,11 @@ // Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors // MIT License. See license.txt -get_server_fields = function(method, arg, table_field, doc, dt, dn, allow_edit, call_back) { +window.get_server_fields = function(method, arg, table_field, doc, dt, dn, allow_edit, call_back) { console.warn("This function 'get_server_fields' has been deprecated and will be removed soon."); frappe.dom.freeze(); if($.isPlainObject(arg)) arg = JSON.stringify(arg); - return $c('runserverobj', - args={'method': method, 'docs': JSON.stringify(doc), 'arg': arg }, + return $c('runserverobj', {'method': method, 'docs': JSON.stringify(doc), 'arg': arg }, function(r, rt) { frappe.dom.unfreeze(); if (r.message) { @@ -24,12 +23,11 @@ get_server_fields = function(method, arg, table_field, doc, dt, dn, allow_edit, doc = locals[doc.doctype][doc.name]; call_back(doc, dt, dn); } - } - ); + }); } -set_multiple = function (dt, dn, dict, table_field) { +window.set_multiple = function (dt, dn, dict, table_field) { var d = locals[dt][dn]; for(var key in dict) { d[key] = dict[key]; @@ -40,7 +38,7 @@ set_multiple = function (dt, dn, dict, table_field) { } } -refresh_many = function (flist, dn, table_field) { +window.refresh_many = function (flist, dn, table_field) { for(var i in flist) { if (table_field) refresh_field(flist[i], dn, table_field); @@ -49,7 +47,7 @@ refresh_many = function (flist, dn, table_field) { } } -set_field_tip = function(n,txt) { +window.set_field_tip = function(n,txt) { var df = frappe.meta.get_docfield(cur_frm.doctype, n, cur_frm.docname); if(df)df.description = txt; @@ -84,11 +82,11 @@ refresh_field = function(n, docname, table_field) { } } -set_field_options = function(n, txt) { +window.set_field_options = function(n, txt) { cur_frm.set_df_property(n, 'options', txt) } -set_field_permlevel = function(n, level) { +window.set_field_permlevel = function(n, level) { cur_frm.set_df_property(n, 'permlevel', level) } @@ -161,7 +159,7 @@ _f.Frm.prototype.set_currency_labels = function(fields_list, currency, parentfie _f.Frm.prototype.field_map = function(fnames, fn) { if(typeof fnames==='string') { if(fnames == '*') { - fnames = keys(this.fields_dict); + fnames = Object.keys(this.fields_dict); } else { fnames = [fnames]; } @@ -172,7 +170,7 @@ _f.Frm.prototype.field_map = function(fnames, fn) { if(field) { fn(field); cur_frm.refresh_field(fieldname); - }; + } } } @@ -192,14 +190,14 @@ _f.Frm.prototype.set_df_property = function(fieldname, property, value, docname, var df = this.get_docfield(fieldname); } else { var grid = cur_frm.fields_dict[table_field].grid, - fname = frappe.utils.filter_dict(grid.docfields, {'fieldname': fieldname}); + fname = frappe.utils.filter_dict(grid.docfields, {'fieldname': fieldname}); if (fname && fname.length) var df = frappe.meta.get_docfield(fname[0].parent, fieldname, docname); } if(df && df[property] != value) { df[property] = value; refresh_field(fieldname, table_field); - }; + } } _f.Frm.prototype.toggle_enable = function(fnames, enable) { @@ -279,7 +277,7 @@ _f.Frm.prototype.set_value = function(field, value, if_missing) { } } } else { - msgprint("Field " + f + " not found."); + frappe.msgprint("Field " + f + " not found."); throw "frm.set_value"; } } @@ -318,7 +316,7 @@ _f.Frm.prototype.call = function(opts, args, callback) { opts.child = locals[opts.child.doctype][opts.child.name]; var std_field_list = ["doctype"].concat(frappe.model.std_fields_list); - for (key in r.message) { + for (var key in r.message) { if (std_field_list.indexOf(key)===-1) { opts.child[key] = r.message[key]; } @@ -409,6 +407,7 @@ _f.Frm.prototype.has_mapper = function() { _f.Frm.prototype.set_indicator_formatter = function(fieldname, get_color, get_text) { // get doctype from parent + var doctype; if(frappe.meta.docfield_map[this.doctype][fieldname]) { doctype = this.doctype; } else { @@ -472,7 +471,7 @@ _f.Frm.prototype.make_new = function(doctype) { this.custom_buttons[this.custom_make_buttons[doctype]].trigger('click'); } else { frappe.model.with_doctype(doctype, function() { - new_doc = frappe.model.get_new_doc(doctype); + var new_doc = frappe.model.get_new_doc(doctype); // set link fields (if found) frappe.get_meta(doctype).fields.forEach(function(df) { diff --git a/frappe/public/js/legacy/datatype.js b/frappe/public/js/legacy/datatype.js index 6834d206c0..bf7024d6e8 100644 --- a/frappe/public/js/legacy/datatype.js +++ b/frappe/public/js/legacy/datatype.js @@ -17,7 +17,7 @@ function toTitle(str){ var word_in = str.split(" "); var word_out = []; - for(w in word_in){ + for(var w in word_in){ word_out[w] = word_in[w].charAt(0).toUpperCase() + word_in[w].slice(1); } @@ -75,12 +75,7 @@ var crop = function(s, len) { return s; } - -function keys(obj) { - var mykeys=[]; - for (var key in obj) mykeys[mykeys.length]=key; - return mykeys; -} +console.warn('The global `keys` has been deprecated. Please use `Object.keys` instead'); function has_words(list, item) { if(!item) return true; @@ -100,7 +95,6 @@ function has_common(list1, list2) { return false; } -var inList = in_list; // bc function add_lists(l1, l2) { return [].concat(l1).concat(l2); } diff --git a/frappe/public/js/legacy/dom.js b/frappe/public/js/legacy/dom.js index 25fc294214..13d1ab2942 100644 --- a/frappe/public/js/legacy/dom.js +++ b/frappe/public/js/legacy/dom.js @@ -66,7 +66,7 @@ function $bg(e,w) { if(e && e.style && w)e.style.backgroundColor = w; } function $y(ele, s) { if(ele && s) { for(var i in s) ele.style[i]=s[i]; - }; + } return ele; } @@ -86,7 +86,7 @@ function make_table(parent, nr, nc, table_width, widths, cell_style, table_style c.style.width = widths[ci]; } if(cell_style) { - for(var s in cell_style) c.style[s] = cell_style[s]; + for(var s in cell_style) c.style[s] = cell_style[s]; } } } @@ -164,5 +164,5 @@ frappe.urllib = { } } -get_url_arg = frappe.urllib.get_arg; -get_url_dict = frappe.urllib.get_dict; +window.get_url_arg = frappe.urllib.get_arg; +window.get_url_dict = frappe.urllib.get_dict; diff --git a/frappe/public/js/legacy/form.js b/frappe/public/js/legacy/form.js index 8aa1deb45c..5bd3c5b175 100644 --- a/frappe/public/js/legacy/form.js +++ b/frappe/public/js/legacy/form.js @@ -60,17 +60,17 @@ _f.Frm = function(doctype, parent, in_form) { _f.Frm.prototype.check_doctype_conflict = function(docname) { var me = this; if(this.doctype=='DocType' && docname=='DocType') { - msgprint(__('Allowing DocType, DocType. Be careful!')) + frappe.msgprint(__('Allowing DocType, DocType. Be careful!')) } else if(this.doctype=='DocType') { if (frappe.views.formview[docname] || frappe.pages['List/'+docname]) { window.location.reload(); - // msgprint(__("Cannot open {0} when its instance is open", ['DocType'])) + // frappe.msgprint(__("Cannot open {0} when its instance is open", ['DocType'])) // throw 'doctype open conflict' } } else { if (frappe.views.formview.DocType && frappe.views.formview.DocType.frm.opendocs[this.doctype]) { window.location.reload(); - // msgprint(__("Cannot open instance when its {0} is open", ['DocType'])) + // frappe.msgprint(__("Cannot open instance when its {0} is open", ['DocType'])) // throw 'doctype open conflict' } } @@ -136,12 +136,12 @@ _f.Frm.prototype.setup_drag_drop = function() { e.preventDefault(); if(me.doc.__islocal) { - msgprint(__("Please save before attaching.")); + frappe.msgprint(__("Please save before attaching.")); throw "attach error"; } if(me.attachments.max_reached()) { - msgprint(__("Maximum Attachment Limit for this record reached.")); + frappe.msgprint(__("Maximum Attachment Limit for this record reached.")); throw "attach error"; } @@ -173,7 +173,7 @@ _f.Frm.prototype.print_doc = function() { return; } if(!frappe.model.can_print(this.doc.doctype, this)) { - msgprint(__("You are not allowed to print this document")); + frappe.msgprint(__("You are not allowed to print this document")); return; } @@ -189,7 +189,7 @@ _f.Frm.prototype.set_hidden = function(status) { form_page.toggleClass('hidden', this.hidden); this.toolbar.refresh(); if(status===true) { - msg = __('Edit {0} properties', [__(this.doctype)]); + var msg = __('Edit {0} properties', [__(this.doctype)]); this.layout.show_message(''); } else { @@ -393,12 +393,11 @@ _f.Frm.prototype.refresh = function(docname) { if(docname) { // record switch - if(this.docname != docname && (!this.meta.in_dialog || this.in_form) && - !this.meta.istable) { - frappe.utils.scroll_to(0); - this.hide_print(); - } - frappe.ui.form.close_grid_form(); + if(this.docname != docname && (!this.meta.in_dialog || this.in_form) && !this.meta.istable) { + frappe.utils.scroll_to(0); + this.hide_print(); + } + frappe.ui.form.close_grid_form(); this.docname = docname; } @@ -691,7 +690,8 @@ _f.Frm.prototype.reload_doc = function() { } } -var validated; +console.warn('The global `validated` has been deprecated. Please use `frappe.validated` instead.'); +frappe.validated = 0; _f.Frm.prototype.save = function(save_action, callback, btn, on_error) { btn && $(btn).prop("disabled", true); $(document.activeElement).blur(); @@ -728,12 +728,12 @@ _f.Frm.prototype._save = function(save_action, callback, btn, on_error) { if(save_action != "Update") { // validate - validated = true; + frappe.validated = true; $.when(this.script_manager.trigger("validate"), this.script_manager.trigger("before_save")) .done(function() { // done is called after all ajaxes in validate & before_save are completed :) - if(!validated) { + if(!frappe.validated) { btn && $(btn).prop("disabled", false); if(on_error) { on_error(); @@ -754,9 +754,9 @@ _f.Frm.prototype.savesubmit = function(btn, callback, on_error) { var me = this; this.validate_form_action("Submit"); frappe.confirm(__("Permanently Submit {0}?", [this.docname]), function() { - validated = true; + frappe.validated = true; me.script_manager.trigger("before_submit").done(function() { - if(!validated) { + if(!frappe.validated) { if(on_error) on_error(); return; @@ -777,9 +777,9 @@ _f.Frm.prototype.savecancel = function(btn, callback, on_error) { var me = this; this.validate_form_action('Cancel'); frappe.confirm(__("Permanently Cancel {0}?", [this.docname]), function() { - validated = true; + frappe.validated = true; me.script_manager.trigger("before_cancel").done(function() { - if(!validated) { + if(!frappe.validated) { if(on_error) on_error(); return; @@ -815,12 +815,12 @@ _f.Frm.prototype.amend_doc = function() { } this.validate_form_action("Amend"); var me = this; - var fn = function(newdoc) { - newdoc.amended_from = me.docname; - if(me.fields_dict && me.fields_dict['amendment_date']) - newdoc.amendment_date = dateutil.obj_to_str(new Date()); - } - this.copy_doc(fn, 1); + var fn = function(newdoc) { + newdoc.amended_from = me.docname; + if(me.fields_dict && me.fields_dict['amendment_date']) + newdoc.amendment_date = frappe.datetime.obj_to_str(new Date()); + } + this.copy_doc(fn, 1); frappe.utils.play_sound("click"); } diff --git a/frappe/public/js/legacy/handler.js b/frappe/public/js/legacy/handler.js index 022f6ee945..61d197b23a 100644 --- a/frappe/public/js/legacy/handler.js +++ b/frappe/public/js/legacy/handler.js @@ -20,7 +20,7 @@ function $c_obj(doc, method, arg, callback, no_spinner, freeze_msg, btn) { if(arg && typeof arg!='string') arg = JSON.stringify(arg); - args = { + var args = { cmd:'runserverobj', args: arg, method: method diff --git a/frappe/public/js/legacy/layout.js b/frappe/public/js/legacy/layout.js index 627d4a521f..c68e0c916c 100644 --- a/frappe/public/js/legacy/layout.js +++ b/frappe/public/js/legacy/layout.js @@ -43,6 +43,7 @@ Layout.prototype.addcell = function(width) { return this.cur_row.addCell(width); } +// eslint-disable-next-line Layout.prototype.setcolour = function(col) { $bg(cc,col); } Layout.prototype.show = function() { $(this.wrapper).toggle(false); } @@ -89,7 +90,7 @@ function LayoutCell(layout, layoutRow, width) { if(width) { // add '%' if user has forgotten var w = width + ''; if(w.substr(w.length-2, 2) != 'px') { - if(w.substr(w.length-1, 1) != "%") {width = width + '%'}; + if(w.substr(w.length-1, 1) != "%") {width = width + '%'} } } diff --git a/frappe/public/js/legacy/print_format.js b/frappe/public/js/legacy/print_format.js index 3a28fb1428..c4c060fa0e 100644 --- a/frappe/public/js/legacy/print_format.js +++ b/frappe/public/js/legacy/print_format.js @@ -34,7 +34,7 @@ _p.go = function(html) { _p.preview = function(html) { var w = window.open(); if(!w) { - msgprint(__("Please enable pop-ups")); + frappe.msgprint(__("Please enable pop-ups")); return; } w.document.write(html); @@ -113,7 +113,7 @@ $.extend(_p, { fmtname= "Standard"; } - args = { + var args = { fmtname: fmtname, onload: onload, no_letterhead: no_letterhead, @@ -121,12 +121,12 @@ $.extend(_p, { }; if(!cur_frm) { - msgprint(__("No document selected")); + frappe.msgprint(__("No document selected")); return; } if(!frappe.model.can_print(cur_frm.doctype, cur_frm)) { - msgprint(__("You are not allowed to print this document")); + frappe.msgprint(__("You are not allowed to print this document")); return; } @@ -145,7 +145,7 @@ $.extend(_p, { } else { var print_format_doc = locals["Print Format"][args.fmtname]; if(!print_format_doc) { - msgprint(__("Unknown Print Format: {0}", [args.fmtname])); + frappe.msgprint(__("Unknown Print Format: {0}", [args.fmtname])); return; } args.onload(_p.render({ @@ -220,7 +220,7 @@ $.extend(_p, { } if(args.doc && cint(args.doc.docstatus)==0 && is_doctype_submittable) { - draft = _p.head_banner_format(); + var draft = _p.head_banner_format(); draft = draft.replace("{{HEAD}}", "DRAFT"); draft = draft.replace("{{DESCRIPTION}}", "This box will go away after the document is submitted."); return draft; @@ -236,7 +236,7 @@ $.extend(_p, { */ show_archived: function(args) { if(args.doc && args.doc.__archived) { - archived = _p.head_banner_format(); + var archived = _p.head_banner_format(); archived = archived.replace("{{HEAD}}", "ARCHIVED"); archived = archived.replace("{{DESCRIPTION}}", "You must restore this document to make it editable."); return archived; @@ -252,7 +252,7 @@ $.extend(_p, { */ show_cancelled: function(args) { if(args.doc && args.doc.docstatus==2) { - cancelled = _p.head_banner_format(); + var cancelled = _p.head_banner_format(); cancelled = cancelled.replace("{{HEAD}}", "CANCELLED"); cancelled = cancelled.replace("{{DESCRIPTION}}", "You must amend this document to make it editable."); return cancelled; @@ -267,7 +267,7 @@ $.extend(_p, { var body_style = ''; var style_list = container.getElementsByTagName('style'); while(style_list && style_list.length>0) { - for(i in style_list) { + for(var i in style_list) { if(style_list[i] && style_list[i].innerHTML) { body_style += style_list[i].innerHTML; var parent = style_list[i].parentNode; @@ -282,7 +282,7 @@ $.extend(_p, { } // Concatenate all styles - style_concat = (args.only_body ? '' : _p.def_print_style_body) + var style_concat = (args.only_body ? '' : _p.def_print_style_body) + _p.def_print_style_other + args.style + body_style; return style_concat; @@ -625,7 +625,7 @@ $.extend(_p, { // If only one table is passed layout.cur_cell.appendChild(t); } else { - page_break = '\n\ + var page_break = '\n\ '; @@ -662,7 +662,7 @@ $.extend(_p, { // If value or a numeric type then proceed // Add field table - row = _p.field_tab(layout.cur_cell); + var row = _p.field_tab(layout.cur_cell); // Add label row.cells[0].innerHTML = __(f.label ? f.label : f.fieldname); diff --git a/frappe/public/js/legacy/print_table.js b/frappe/public/js/legacy/print_table.js index d6d7d0578c..3c8562b1a6 100644 --- a/frappe/public/js/legacy/print_table.js +++ b/frappe/public/js/legacy/print_table.js @@ -141,7 +141,7 @@ frappe.printTable = Class.extend({ // get from doctype and redistribute to fit 100% if(!this.widths) { this.widths = $.map(this.columns, function(fieldname, ci) { - df = frappe.meta.docfield_map[me.tabletype][fieldname]; + var df = frappe.meta.docfield_map[me.tabletype][fieldname]; return df && df.print_width || (fieldname=="Sr" ? 30 : 80); }); @@ -192,7 +192,7 @@ frappe.printTable = Class.extend({ }, }) -function print_table(dt, dn, fieldname, tabletype, cols, head_labels, widths, condition, cssClass, modifier) { +window.print_table = function print_table(dt, dn, fieldname, tabletype, cols, head_labels, widths, condition, cssClass, modifier) { return new frappe.printTable({ doctype: dt, docname: dn, diff --git a/frappe/public/js/frappe/views/kanban/fluxify.min.js b/frappe/public/js/lib/fluxify.min.js similarity index 100% rename from frappe/public/js/frappe/views/kanban/fluxify.min.js rename to frappe/public/js/lib/fluxify.min.js diff --git a/frappe/templates/includes/contact.js b/frappe/templates/includes/contact.js index 869b4dce60..a5974e6725 100644 --- a/frappe/templates/includes/contact.js +++ b/frappe/templates/includes/contact.js @@ -8,16 +8,16 @@ frappe.ready(function() { var message = $('[name="message"]').val(); if(!(email && message)) { - msgprint(__("Please enter both your email and message so that we \ + frappe.msgprint(__("Please enter both your email and message so that we \ can get back to you. Thanks!")); return false; } - if(!valid_email(email)) { - msgprint(__("You seem to have written your name instead of your email. \ - Please enter a valid email address so that we can get back.")); - $('[name="email"]').focus(); - return false; + if(!validate_email(email)) { + frappe.msgprint(__("You seem to have written your name instead of your email. \ + Please enter a valid email address so that we can get back.")); + $('[name="email"]').focus(); + return false; } $("#contact-alert").toggle(false); @@ -27,15 +27,15 @@ frappe.ready(function() { message: message, callback: function(r) { if(r.message==="okay") { - msgprint(__("Thank you for your message")); + frappe.msgprint(__("Thank you for your message")); } else { - msgprint(__("There were errors")); + frappe.msgprint(__("There were errors")); console.log(r.exc); } $(':input').val(''); } }, this); - return false; + return false; }); }); diff --git a/frappe/website/doctype/web_form/web_form.js b/frappe/website/doctype/web_form/web_form.js index 0162e5ae7f..67f32ef06f 100644 --- a/frappe/website/doctype/web_form/web_form.js +++ b/frappe/website/doctype/web_form/web_form.js @@ -1,80 +1,80 @@ frappe.web_form = { - set_fieldname_select: function(frm) { - var me = this, - doc = frm.doc; - if (doc.doc_type) { - frappe.model.with_doctype(doc.doc_type, function() { - var fields = $.map(frappe.get_doc("DocType", frm.doc.doc_type).fields, function(d) { - if (frappe.model.no_value_type.indexOf(d.fieldtype) === -1 || - d.fieldtype === 'Table') { - return { label: d.label + ' (' + d.fieldtype + ')', value: d.fieldname } - } else { - return null; - } - }) - var currency_fields = $.map(frappe.get_doc("DocType", frm.doc.doc_type).fields, function(d) { - if (d.fieldtype === 'Currency' || d.fieldtype === 'Float') { - return { label: d.label, value: d.fieldname } - } else { - return null; - } - }) - frappe.meta.get_docfield("Web Form Field", "fieldname", frm.doc.name).options = [""].concat(fields); - frappe.meta.get_docfield("Web Form", "amount_field", frm.doc.name).options = [""].concat(currency_fields); - frm.refresh_field("amount_field"); - }); - } - } + set_fieldname_select: function(frm) { + var me = this, + doc = frm.doc; + if (doc.doc_type) { + frappe.model.with_doctype(doc.doc_type, function() { + var fields = $.map(frappe.get_doc("DocType", frm.doc.doc_type).fields, function(d) { + if (frappe.model.no_value_type.indexOf(d.fieldtype) === -1 || + d.fieldtype === 'Table') { + return { label: d.label + ' (' + d.fieldtype + ')', value: d.fieldname } + } else { + return null; + } + }) + var currency_fields = $.map(frappe.get_doc("DocType", frm.doc.doc_type).fields, function(d) { + if (d.fieldtype === 'Currency' || d.fieldtype === 'Float') { + return { label: d.label, value: d.fieldname } + } else { + return null; + } + }) + frappe.meta.get_docfield("Web Form Field", "fieldname", frm.doc.name).options = [""].concat(fields); + frappe.meta.get_docfield("Web Form", "amount_field", frm.doc.name).options = [""].concat(currency_fields); + frm.refresh_field("amount_field"); + }); + } + } } frappe.ui.form.on("Web Form", { - refresh: function(frm) { - // show is-standard only if developer mode - frm.get_field("is_standard").toggle(frappe.boot.developer_mode); + refresh: function(frm) { + // show is-standard only if developer mode + frm.get_field("is_standard").toggle(frappe.boot.developer_mode); - frappe.web_form.set_fieldname_select(frm); + frappe.web_form.set_fieldname_select(frm); - if (frm.doc.is_standard && !frappe.boot.developer_mode) { - frm.set_read_only(); - frm.disable_save(); - } - }, + if (frm.doc.is_standard && !frappe.boot.developer_mode) { + frm.set_read_only(); + frm.disable_save(); + } + }, - title: function(frm) { - if (frm.doc.__islocal) { - var page_name = frm.doc.title.toLowerCase().replace(/ /g, "-"); - frm.set_value("route", page_name); - frm.set_value("success_url", "/" + page_name); - } - }, + title: function(frm) { + if (frm.doc.__islocal) { + var page_name = frm.doc.title.toLowerCase().replace(/ /g, "-"); + frm.set_value("route", page_name); + frm.set_value("success_url", "/" + page_name); + } + }, - doc_type: function(frm) { - frappe.web_form.set_fieldname_select(frm); - } + doc_type: function(frm) { + frappe.web_form.set_fieldname_select(frm); + } }); frappe.ui.form.on("Web Form Field", { - fieldtype: function(frm, doctype, name) { - var doc = frappe.get_doc(doctype, name); - if (fieldtype === 'Section Break' || fieldtype === 'Section Break') { - doc.fieldname = ''; - frm.refresh_field("web_form_fields"); - } - }, - fieldname: function(frm, doctype, name) { - var doc = frappe.get_doc(doctype, name); - var df = $.map(frappe.get_doc("DocType", frm.doc.doc_type).fields, function(d) { - return doc.fieldname == d.fieldname ? d : null; - })[0]; + fieldtype: function(frm, doctype, name) { + var doc = frappe.get_doc(doctype, name); + if (['Section Break', 'Column Break', 'Page Break'].includes(doc.fieldtype)) { + doc.fieldname = ''; + frm.refresh_field("web_form_fields"); + } + }, + fieldname: function(frm, doctype, name) { + var doc = frappe.get_doc(doctype, name); + var df = $.map(frappe.get_doc("DocType", frm.doc.doc_type).fields, function(d) { + return doc.fieldname == d.fieldname ? d : null; + })[0]; - doc.label = df.label; - doc.reqd = df.reqd; - doc.options = df.options; - doc.fieldtype = frappe.meta.get_docfield("Web Form Field", "fieldtype") - .options.split("\n").indexOf(df.fieldtype) === -1 ? "Data" : df.fieldtype; - doc.description = df.description; - doc["default"] = df["default"]; + doc.label = df.label; + doc.reqd = df.reqd; + doc.options = df.options; + doc.fieldtype = frappe.meta.get_docfield("Web Form Field", "fieldtype") + .options.split("\n").indexOf(df.fieldtype) === -1 ? "Data" : df.fieldtype; + doc.description = df.description; + doc["default"] = df["default"]; - } + } }); \ No newline at end of file diff --git a/frappe/website/doctype/website_settings/website_settings.js b/frappe/website/doctype/website_settings/website_settings.js index cf8d9497f3..5200a8aaf4 100644 --- a/frappe/website/doctype/website_settings/website_settings.js +++ b/frappe/website/doctype/website_settings/website_settings.js @@ -14,7 +14,7 @@ // doctype:"Website Settings" // }, // callback: function(r) { -// if(!r.exc) { msgprint(__("Exported")); } +// if(!r.exc) { frappe.msgprint(__("Exported")); } // } // }) // }) @@ -81,7 +81,7 @@ $.extend(cur_frm.cscript, { cur_frm.cscript.set_banner_from_image = function(doc) { if(!doc.banner_image) { - msgprint(__("Select a Brand Image first.")); + frappe.msgprint(__("Select a Brand Image first.")); } var src = doc.banner_image; cur_frm.set_value("brand_html", " maxlength-1) { $(this).val($(this).val().substr(0, maxlength-1)); - }; + } }).each(function() { set_mandatory_class(this); }); // if changed, set dirty flag @@ -104,7 +103,7 @@ frappe.ready(function() { return false; }); - show_slide = function(idx) { + var show_slide = function(idx) { // hide all sections $('.web-form-page').addClass('hidden'); @@ -175,7 +174,7 @@ frappe.ready(function() { // check if child table has value var has_value = false; - for(key in d) { + for(var key in d) { if(typeof d[key]==='string') { d[key] = d[key].trim(); } @@ -286,9 +285,9 @@ frappe.ready(function() { $(".comments, .introduction, .page-head").addClass("hide"); scroll(0, 0); set_message(frappe.success_link, true); - } else { + } else { set_message(__('Saved')); - } + } if(frappe.is_new && frappe.login_required) { // reload page (with ID) @@ -298,13 +297,13 @@ frappe.ready(function() { // redirect to payment window.location.href = data.message; } - } else { + } else { frappe.msgprint(__('There were errors. Please report this.')); - } - }, - always: function() { - window.saving = false; - } + } + }, + always: function() { + window.saving = false; + } }); return true; } diff --git a/frappe/website/js/website.js b/frappe/website/js/website.js index cfbe6beb86..5f7fd4d634 100644 --- a/frappe/website/js/website.js +++ b/frappe/website/js/website.js @@ -159,12 +159,9 @@ $.extend(frappe, { .html('
').appendTo(document.body); }, - hide_message: function(text) { - $('.message-overlay').remove(); - }, get_sid: function() { var sid = getCookie("sid"); - return sid && sid!=="Guest"; + return sid && sid !== "Guest"; }, get_modal: function(title, body_html) { var modal = $('
' +text+'\ @@ -366,7 +363,7 @@ function ask_to_login() { // check if logged in? $(document).ready(function() { window.full_name = getCookie("full_name"); - window.logged_in = getCookie("sid") && getCookie("sid")!=="Guest"; + var logged_in = getCookie("sid") && getCookie("sid") !== "Guest"; $("#website-login").toggleClass("hide", logged_in ? true : false); $("#website-post-login").toggleClass("hide", logged_in ? false : true); $(".logged-in").toggleClass("hide", logged_in ? false : true); diff --git a/socketio.js b/socketio.js index 3b43fa7e04..cd3eb64aa8 100644 --- a/socketio.js +++ b/socketio.js @@ -11,13 +11,13 @@ var flags = {}; var subscriber = redis.createClient(conf.redis_socketio || conf.redis_async_broker_port); // serve socketio -http.listen(conf.socketio_port, function(){ - console.log('listening on *:', conf.socketio_port); +http.listen(conf.socketio_port, function() { + console.log('listening on *:', conf.socketio_port); //eslint-disable-line }); // test route -app.get('/', function(req, res){ - res.sendfile('index.html'); +app.get('/', function(req, res) { + res.sendfile('index.html'); }); // on socket connection @@ -199,8 +199,8 @@ function get_site_name(socket) { function get_hostname(url) { if (!url) return undefined; if (url.indexOf("://") > -1) { - url = url.split('/')[2]; - } + url = url.split('/')[2]; + } return ( url.match(/:/g) ) ? url.slice( 0, url.indexOf(":") ) : url }