You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

980 line
24 KiB

  1. // Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
  2. // MIT License. See license.txt
  3. /* Form page structure
  4. + this.parent (either FormContainer or Dialog)
  5. + this.wrapper
  6. + this.toolbar
  7. + this.form_wrapper
  8. + this.head
  9. + this.body
  10. + this.layout
  11. + this.sidebar
  12. + this.footer
  13. */
  14. frappe.provide('_f');
  15. frappe.provide('frappe.ui.form');
  16. frappe.ui.form.Controller = Class.extend({
  17. init: function(opts) {
  18. $.extend(this, opts);
  19. }
  20. });
  21. _f.frms = {};
  22. _f.Frm = function(doctype, parent, in_form) {
  23. this.docname = '';
  24. this.doctype = doctype;
  25. this.hidden = false;
  26. this.refresh_if_stale_for = 120;
  27. var me = this;
  28. this.opendocs = {};
  29. this.custom_buttons = {};
  30. this.sections = [];
  31. this.grids = [];
  32. this.cscript = new frappe.ui.form.Controller({frm:this});
  33. this.events = {};
  34. this.pformat = {};
  35. this.fetch_dict = {};
  36. this.parent = parent;
  37. this.tinymce_id_list = [];
  38. this.setup_meta(doctype);
  39. // show in form instead of in dialog, when called using url (router.js)
  40. this.in_form = in_form ? true : false;
  41. // notify on rename
  42. var me = this;
  43. $(document).on('rename', function(event, dt, old_name, new_name) {
  44. if(dt==me.doctype)
  45. me.rename_notify(dt, old_name, new_name);
  46. });
  47. };
  48. _f.Frm.prototype.check_doctype_conflict = function(docname) {
  49. var me = this;
  50. if(this.doctype=='DocType' && docname=='DocType') {
  51. frappe.msgprint(__('Allowing DocType, DocType. Be careful!'));
  52. } else if(this.doctype=='DocType') {
  53. if (frappe.views.formview[docname] || frappe.pages['List/'+docname]) {
  54. window.location.reload();
  55. // frappe.msgprint(__("Cannot open {0} when its instance is open", ['DocType']))
  56. // throw 'doctype open conflict'
  57. }
  58. } else {
  59. if (frappe.views.formview.DocType && frappe.views.formview.DocType.frm.opendocs[this.doctype]) {
  60. window.location.reload();
  61. // frappe.msgprint(__("Cannot open instance when its {0} is open", ['DocType']))
  62. // throw 'doctype open conflict'
  63. }
  64. }
  65. };
  66. _f.Frm.prototype.setup = function() {
  67. var me = this;
  68. this.fields = [];
  69. this.fields_dict = {};
  70. this.state_fieldname = frappe.workflow.get_state_fieldname(this.doctype);
  71. // wrapper
  72. this.wrapper = this.parent;
  73. this.$wrapper = $(this.wrapper);
  74. frappe.ui.make_app_page({
  75. parent: this.wrapper,
  76. single_column: this.meta.hide_toolbar
  77. });
  78. this.page = this.wrapper.page;
  79. this.layout_main = this.page.main.get(0);
  80. this.toolbar = new frappe.ui.form.Toolbar({
  81. frm: this,
  82. page: this.page
  83. });
  84. // print layout
  85. this.setup_print_layout();
  86. // 2 column layout
  87. this.setup_std_layout();
  88. // client script must be called after "setup" - there are no fields_dict attached to the frm otherwise
  89. this.script_manager = new frappe.ui.form.ScriptManager({
  90. frm: this
  91. });
  92. this.script_manager.setup();
  93. this.watch_model_updates();
  94. if(!this.meta.hide_toolbar) {
  95. this.footer = new frappe.ui.form.Footer({
  96. frm: this,
  97. parent: $('<div>').appendTo(this.page.main.parent())
  98. });
  99. $("body").attr("data-sidebar", 1);
  100. }
  101. this.setup_drag_drop();
  102. this.setup_done = true;
  103. };
  104. _f.Frm.prototype.setup_drag_drop = function() {
  105. var me = this;
  106. this.$wrapper.on('dragenter dragover', false)
  107. .on('drop', function (e) {
  108. var dataTransfer = e.originalEvent.dataTransfer;
  109. if (!(dataTransfer && dataTransfer.files && dataTransfer.files.length > 0)) {
  110. return;
  111. }
  112. e.stopPropagation();
  113. e.preventDefault();
  114. if(me.doc.__islocal) {
  115. frappe.msgprint(__("Please save before attaching."));
  116. throw "attach error";
  117. }
  118. if(me.attachments.max_reached()) {
  119. frappe.msgprint(__("Maximum Attachment Limit for this record reached."));
  120. throw "attach error";
  121. }
  122. frappe.upload.make({
  123. args: me.attachments.get_args(),
  124. files: dataTransfer.files,
  125. callback: function(attachment, r) {
  126. me.attachments.attachment_uploaded(attachment, r);
  127. }
  128. });
  129. });
  130. };
  131. _f.Frm.prototype.setup_print_layout = function() {
  132. var me = this;
  133. this.print_preview = new frappe.ui.form.PrintPreview({
  134. frm: this
  135. });
  136. // show edit button for print view
  137. this.page.wrapper.on('view-change', function() {
  138. me.toolbar.set_primary_action();
  139. });
  140. };
  141. _f.Frm.prototype.print_doc = function() {
  142. if(this.print_preview.wrapper.is(":visible")) {
  143. this.hide_print();
  144. return;
  145. }
  146. if(!frappe.model.can_print(this.doc.doctype, this)) {
  147. frappe.msgprint(__("You are not allowed to print this document"));
  148. return;
  149. }
  150. this.print_preview.refresh_print_options().trigger("change");
  151. this.page.set_view("print");
  152. this.print_preview.set_user_lang();
  153. };
  154. _f.Frm.prototype.hide_print = function() {
  155. if(this.setup_done && this.page.current_view_name==="print") {
  156. this.page.set_view(this.page.previous_view_name==="print" ?
  157. "main" : (this.page.previous_view_name || "main"));
  158. }
  159. };
  160. _f.Frm.prototype.watch_model_updates = function() {
  161. // watch model updates
  162. var me = this;
  163. // on main doc
  164. frappe.model.on(me.doctype, "*", function(fieldname, value, doc) {
  165. // set input
  166. if(doc.name===me.docname) {
  167. me.dirty();
  168. me.fields_dict[fieldname]
  169. && me.fields_dict[fieldname].refresh(fieldname);
  170. me.layout.refresh_dependency();
  171. return me.script_manager.trigger(fieldname, doc.doctype, doc.name);
  172. }
  173. });
  174. // on table fields
  175. var table_fields = frappe.get_children("DocType", me.doctype, "fields", {fieldtype:"Table"});
  176. // using $.each to preserve df via closure
  177. $.each(table_fields, function(i, df) {
  178. frappe.model.on(df.options, "*", function(fieldname, value, doc) {
  179. if(doc.parent===me.docname && doc.parentfield===df.fieldname) {
  180. me.dirty();
  181. me.fields_dict[df.fieldname].grid.set_value(fieldname, value, doc);
  182. me.script_manager.trigger(fieldname, doc.doctype, doc.name);
  183. }
  184. });
  185. });
  186. };
  187. _f.Frm.prototype.setup_std_layout = function() {
  188. this.form_wrapper = $('<div></div>').appendTo(this.layout_main);
  189. this.body = $('<div></div>').appendTo(this.form_wrapper);
  190. // only tray
  191. this.meta.section_style='Simple'; // always simple!
  192. // layout
  193. this.layout = new frappe.ui.form.Layout({
  194. parent: this.body,
  195. doctype: this.doctype,
  196. frm: this,
  197. with_dashboard: true
  198. });
  199. this.layout.make();
  200. this.fields_dict = this.layout.fields_dict;
  201. this.fields = this.layout.fields_list;
  202. this.document_flow = new frappe.ui.form.DocumentFlow({
  203. frm: this
  204. });
  205. this.dashboard = new frappe.ui.form.Dashboard({
  206. frm: this,
  207. });
  208. // state
  209. this.states = new frappe.ui.form.States({
  210. frm: this
  211. });
  212. };
  213. // email the form
  214. _f.Frm.prototype.email_doc = function(message) {
  215. new frappe.views.CommunicationComposer({
  216. doc: this.doc,
  217. frm: this,
  218. subject: __(this.meta.name) + ': ' + this.docname,
  219. recipients: this.doc.email || this.doc.email_id || this.doc.contact_email,
  220. attach_document_print: true,
  221. message: message,
  222. real_name: this.doc.real_name || this.doc.contact_display || this.doc.contact_name
  223. });
  224. };
  225. // rename the form
  226. _f.Frm.prototype.rename_doc = function() {
  227. frappe.model.rename_doc(this.doctype, this.docname);
  228. };
  229. _f.Frm.prototype.share_doc = function() {
  230. this.shared.show();
  231. };
  232. // notify this form of renamed records
  233. _f.Frm.prototype.rename_notify = function(dt, old, name) {
  234. // from form
  235. if(this.meta.istable)
  236. return;
  237. if(this.docname == old)
  238. this.docname = name;
  239. else
  240. return;
  241. // cleanup
  242. if(this && this.opendocs[old] && frappe.meta.docfield_copy[dt]) {
  243. // delete docfield copy
  244. frappe.meta.docfield_copy[dt][name] = frappe.meta.docfield_copy[dt][old];
  245. delete frappe.meta.docfield_copy[dt][old];
  246. }
  247. delete this.opendocs[old];
  248. this.opendocs[name] = true;
  249. if(this.meta.in_dialog || !this.in_form) {
  250. return;
  251. }
  252. frappe.re_route[window.location.hash] = '#Form/' + encodeURIComponent(this.doctype) + '/' + encodeURIComponent(name);
  253. frappe.set_route('Form', this.doctype, name);
  254. };
  255. // SETUP
  256. _f.Frm.prototype.setup_meta = function(doctype) {
  257. this.meta = frappe.get_doc('DocType',this.doctype);
  258. this.perm = frappe.perm.get_perm(this.doctype); // for create
  259. if(this.meta.istable) { this.meta.in_dialog = 1; }
  260. };
  261. _f.Frm.prototype.refresh_header = function(is_a_different_doc) {
  262. // set title
  263. // main title
  264. if(!this.meta.in_dialog || this.in_form) {
  265. frappe.utils.set_title(this.meta.issingle ? this.doctype : this.docname);
  266. }
  267. // show / hide buttons
  268. if(this.toolbar) {
  269. if (is_a_different_doc) {
  270. this.toolbar.current_status = undefined;
  271. }
  272. this.toolbar.refresh();
  273. }
  274. this.document_flow.refresh();
  275. this.dashboard.refresh();
  276. if(this.meta.is_submittable &&
  277. this.perm[0] && this.perm[0].submit &&
  278. ! this.is_dirty() &&
  279. ! this.is_new() &&
  280. this.doc.docstatus===0) {
  281. this.dashboard.add_comment(__('Submit this document to confirm'), 'orange', true);
  282. }
  283. this.clear_custom_buttons();
  284. this.show_web_link();
  285. };
  286. _f.Frm.prototype.show_web_link = function() {
  287. var doc = this.doc, me = this;
  288. if(!doc.__islocal && doc.__onload && doc.__onload.is_website_generator) {
  289. me.web_link && me.web_link.remove();
  290. if(doc.__onload.published) {
  291. me.add_web_link("/" + doc.route);
  292. }
  293. }
  294. };
  295. _f.Frm.prototype.add_web_link = function(path) {
  296. this.web_link = this.sidebar.add_user_action(__("See on Website"),
  297. function() {}).attr("href", path || this.doc.route).attr("target", "_blank");
  298. };
  299. _f.Frm.prototype.check_doc_perm = function() {
  300. // get perm
  301. var dt = this.parent_doctype?this.parent_doctype : this.doctype;
  302. this.perm = frappe.perm.get_perm(dt, this.doc);
  303. if(!this.perm[0].read) {
  304. return 0;
  305. }
  306. return 1;
  307. };
  308. _f.Frm.prototype.refresh = function(docname) {
  309. var is_a_different_doc = docname ? true : false;
  310. if(docname) {
  311. // record switch
  312. if(this.docname != docname && (!this.meta.in_dialog || this.in_form) && !this.meta.istable) {
  313. frappe.utils.scroll_to(0);
  314. this.hide_print();
  315. }
  316. frappe.ui.form.close_grid_form();
  317. this.docname = docname;
  318. }
  319. cur_frm = this;
  320. if(this.docname) { // document to show
  321. // set the doc
  322. this.doc = frappe.get_doc(this.doctype, this.docname);
  323. // check permissions
  324. if(!this.check_doc_perm()) {
  325. frappe.show_not_permitted(__(this.doctype) + " " + __(this.docname));
  326. return;
  327. }
  328. // read only (workflow)
  329. this.read_only = frappe.workflow.is_read_only(this.doctype, this.docname);
  330. if (this.read_only) this.set_read_only(true);
  331. // check if doctype is already open
  332. if (!this.opendocs[this.docname]) {
  333. this.check_doctype_conflict(this.docname);
  334. } else {
  335. if(this.doc && (!this.doc.__unsaved) && this.doc.__last_sync_on &&
  336. (new Date() - this.doc.__last_sync_on) > (this.refresh_if_stale_for * 1000)) {
  337. this.reload_doc();
  338. return;
  339. }
  340. }
  341. // do setup
  342. if(!this.setup_done) {
  343. this.setup();
  344. }
  345. // load the record for the first time, if not loaded (call 'onload')
  346. this.cscript.is_onload = false;
  347. if(!this.opendocs[this.docname]) {
  348. var me = this;
  349. this.cscript.is_onload = true;
  350. this.setnewdoc();
  351. $(document).trigger("form-load", [this]);
  352. $(this.page.wrapper).on('hide', function(e) {
  353. $(document).trigger("form-unload", [me]);
  354. });
  355. } else {
  356. this.render_form(is_a_different_doc);
  357. if (this.doc.localname) {
  358. // trigger form-rename and remove .localname
  359. delete this.doc.localname;
  360. $(document).trigger("form-rename", [this]);
  361. }
  362. }
  363. // if print format is shown, refresh the format
  364. if(this.print_preview.wrapper.is(":visible")) {
  365. this.print_preview.preview();
  366. }
  367. if(is_a_different_doc) {
  368. if(this.show_print_first && this.doc.docstatus===1) {
  369. // show print view
  370. this.print_doc();
  371. }
  372. }
  373. // set status classes
  374. this.$wrapper.removeClass('validated-form')
  375. .toggleClass('editable-form', this.doc.docstatus===0)
  376. .toggleClass('submitted-form', this.doc.docstatus===1)
  377. .toggleClass('cancelled-form', this.doc.docstatus===2);
  378. this.show_if_needs_refresh();
  379. }
  380. };
  381. _f.Frm.prototype.show_if_needs_refresh = function() {
  382. if(this.doc.__needs_refresh) {
  383. if(this.doc.__unsaved) {
  384. this.dashboard.clear_headline();
  385. this.dashboard.set_headline_alert(__("This form has been modified after you have loaded it")
  386. + '<a class="btn btn-xs btn-primary pull-right" onclick="cur_frm.reload_doc()">'
  387. + __("Refresh") + '</a>', "alert-warning");
  388. } else {
  389. this.reload_doc();
  390. }
  391. }
  392. };
  393. _f.Frm.prototype.render_form = function(is_a_different_doc) {
  394. if(!this.meta.istable) {
  395. this.layout.doc = this.doc;
  396. this.layout.attach_doc_and_docfields();
  397. this.sidebar = new frappe.ui.form.Sidebar({
  398. frm: this,
  399. page: this.page
  400. });
  401. this.sidebar.make();
  402. // clear layout message
  403. this.layout.show_message();
  404. // header must be refreshed before client methods
  405. // because add_custom_button
  406. this.refresh_header(is_a_different_doc);
  407. // call trigger
  408. this.script_manager.trigger("refresh");
  409. // trigger global trigger
  410. // to use this
  411. $(document).trigger('form_refresh', [this]);
  412. // fields
  413. this.refresh_fields();
  414. // call onload post render for callbacks to be fired
  415. if(this.cscript.is_onload) {
  416. this.script_manager.trigger("onload_post_render");
  417. }
  418. // update dashboard after refresh
  419. frappe.timeout(0.1).then(() => this.dashboard.after_refresh());
  420. // focus on first input
  421. if(this.is_new()) {
  422. var first = this.form_wrapper.find('.form-layout input:first');
  423. if(!in_list(["Date", "Datetime"], first.attr("data-fieldtype"))) {
  424. first.focus();
  425. }
  426. }
  427. } else {
  428. this.refresh_header(is_a_different_doc);
  429. }
  430. this.$wrapper.trigger('render_complete');
  431. if(!this.hidden) {
  432. this.layout.show_empty_form_message();
  433. }
  434. this.scroll_to_element();
  435. };
  436. _f.Frm.prototype.refresh_field = function(fname) {
  437. if(this.fields_dict[fname] && this.fields_dict[fname].refresh) {
  438. this.fields_dict[fname].refresh();
  439. this.layout.refresh_dependency();
  440. }
  441. };
  442. _f.Frm.prototype.refresh_fields = function() {
  443. this.layout.refresh(this.doc);
  444. this.layout.primary_button = this.$wrapper.find(".btn-primary");
  445. // cleanup activities after refresh
  446. this.cleanup_refresh(this);
  447. };
  448. _f.Frm.prototype.cleanup_refresh = function() {
  449. var me = this;
  450. if(me.fields_dict['amended_from']) {
  451. if (me.doc.amended_from) {
  452. unhide_field('amended_from');
  453. if (me.fields_dict['amendment_date']) unhide_field('amendment_date');
  454. } else {
  455. hide_field('amended_from');
  456. if (me.fields_dict['amendment_date']) hide_field('amendment_date');
  457. }
  458. }
  459. if(me.fields_dict['trash_reason']) {
  460. if(me.doc.trash_reason && me.doc.docstatus == 2) {
  461. unhide_field('trash_reason');
  462. } else {
  463. hide_field('trash_reason');
  464. }
  465. }
  466. if(me.meta.autoname && me.meta.autoname.substr(0,6)=='field:' && !me.doc.__islocal) {
  467. var fn = me.meta.autoname.substr(6);
  468. if (me.doc[fn]) {
  469. me.toggle_display(fn, false);
  470. }
  471. }
  472. if(me.meta.autoname=="naming_series:" && !me.doc.__islocal) {
  473. me.toggle_display("naming_series", false);
  474. }
  475. };
  476. _f.Frm.prototype.setnewdoc = function() {
  477. // moved this call to refresh function
  478. // this.check_doctype_conflict(docname);
  479. var me = this;
  480. // hide any open grid
  481. this.script_manager.trigger("before_load", this.doctype, this.docname)
  482. .then(() => {
  483. me.script_manager.trigger("onload");
  484. me.opendocs[me.docname] = true;
  485. me.render_form();
  486. frappe.after_ajax(function() {
  487. me.trigger_link_fields();
  488. });
  489. frappe.breadcrumbs.add(me.meta.module, me.doctype);
  490. });
  491. // update seen
  492. if(this.meta.track_seen) {
  493. $('.list-id[data-name="'+ me.docname +'"]').addClass('seen');
  494. }
  495. };
  496. _f.Frm.prototype.trigger_link_fields = function() {
  497. // trigger link fields which have default values set
  498. if (this.is_new() && this.doc.__run_link_triggers) {
  499. $.each(this.fields_dict, function(fieldname, field) {
  500. if (field.df.fieldtype=="Link" && this.doc[fieldname]) {
  501. // triggers add fetch, sets value in model and runs triggers
  502. field.set_value(this.doc[fieldname]);
  503. }
  504. });
  505. delete this.doc.__run_link_triggers;
  506. }
  507. };
  508. _f.Frm.prototype.runscript = function(scriptname, callingfield, onrefresh) {
  509. var me = this;
  510. if(this.docname) {
  511. // send to run
  512. if(callingfield)
  513. $(callingfield.input).set_working();
  514. frappe.call({
  515. method: "runserverobj",
  516. args: {'docs':this.doc, 'method':scriptname },
  517. btn: callingfield.$input,
  518. callback: function(r) {
  519. if(!r.exc) {
  520. if(onrefresh) {
  521. onrefresh(r);
  522. }
  523. me.refresh_fields();
  524. }
  525. }
  526. });
  527. }
  528. };
  529. _f.Frm.prototype.copy_doc = function(onload, from_amend) {
  530. this.validate_form_action("Create");
  531. var newdoc = frappe.model.copy_doc(this.doc, from_amend);
  532. newdoc.idx = null;
  533. newdoc.__run_link_triggers = false;
  534. if(onload) {
  535. onload(newdoc);
  536. }
  537. frappe.set_route('Form', newdoc.doctype, newdoc.name);
  538. };
  539. _f.Frm.prototype.reload_doc = function() {
  540. this.check_doctype_conflict(this.docname);
  541. var me = this;
  542. var onsave = function(r, rtxt) {
  543. me.refresh();
  544. };
  545. if(!me.doc.__islocal) {
  546. frappe.model.remove_from_locals(me.doctype, me.docname);
  547. frappe.model.with_doc(me.doctype, me.docname, function() {
  548. me.refresh();
  549. });
  550. }
  551. };
  552. frappe.validated = 0;
  553. // Proxy for frappe.validated
  554. Object.defineProperty(window, 'validated', {
  555. get: function() {
  556. console.warn('Please use `frappe.validated` instead of `validated`. It will be deprecated soon.');
  557. return frappe.validated;
  558. },
  559. set: function(value) {
  560. console.warn('Please use `frappe.validated` instead of `validated`. It will be deprecated soon.');
  561. frappe.validated = value;
  562. return frappe.validated;
  563. }
  564. });
  565. _f.Frm.prototype.save = function(save_action, callback, btn, on_error) {
  566. let me = this;
  567. return new Promise(resolve => {
  568. btn && $(btn).prop("disabled", true);
  569. $(document.activeElement).blur();
  570. frappe.ui.form.close_grid_form();
  571. // let any pending js process finish
  572. setTimeout(function() {
  573. me._save(save_action, callback, btn, on_error, resolve);
  574. }, 100);
  575. });
  576. };
  577. _f.Frm.prototype._save = function(save_action, callback, btn, on_error, resolve) {
  578. var me = this;
  579. if(!save_action) save_action = "Save";
  580. this.validate_form_action(save_action, resolve);
  581. if((!this.meta.in_dialog || this.in_form) && !this.meta.istable) {
  582. frappe.utils.scroll_to(0);
  583. }
  584. var after_save = function(r) {
  585. if(!r.exc) {
  586. if (["Save", "Update", "Amend"].indexOf(save_action)!==-1) {
  587. frappe.utils.play_sound("click");
  588. }
  589. me.script_manager.trigger("after_save");
  590. me.refresh();
  591. } else {
  592. if(on_error) {
  593. on_error();
  594. }
  595. }
  596. callback && callback(r);
  597. resolve();
  598. };
  599. var fail = () => {
  600. btn && $(btn).prop("disabled", false);
  601. if(on_error) {
  602. on_error();
  603. }
  604. resolve();
  605. };
  606. if(save_action != "Update") {
  607. // validate
  608. frappe.validated = true;
  609. frappe.run_serially([
  610. () => this.script_manager.trigger("validate"),
  611. () => this.script_manager.trigger("before_save"),
  612. () => {
  613. if(!frappe.validated) {
  614. fail();
  615. return;
  616. }
  617. frappe.ui.form.save(me, save_action, after_save, btn);
  618. }
  619. ]).catch(fail);
  620. } else {
  621. frappe.ui.form.save(me, save_action, after_save, btn);
  622. }
  623. };
  624. _f.Frm.prototype.savesubmit = function(btn, callback, on_error) {
  625. var me = this;
  626. this.validate_form_action("Submit");
  627. frappe.confirm(__("Permanently Submit {0}?", [this.docname]), function() {
  628. frappe.validated = true;
  629. me.script_manager.trigger("before_submit").then(function() {
  630. if(!frappe.validated) {
  631. if(on_error)
  632. on_error();
  633. return;
  634. }
  635. return me.save('Submit', function(r) {
  636. if(!r.exc) {
  637. frappe.utils.play_sound("submit");
  638. callback && callback();
  639. me.script_manager.trigger("on_submit");
  640. }
  641. }, btn, on_error);
  642. });
  643. }, on_error);
  644. };
  645. _f.Frm.prototype.savecancel = function(btn, callback, on_error) {
  646. var me = this;
  647. this.validate_form_action('Cancel');
  648. frappe.confirm(__("Permanently Cancel {0}?", [this.docname]), function() {
  649. frappe.validated = true;
  650. me.script_manager.trigger("before_cancel").then(function() {
  651. if(!frappe.validated) {
  652. if(on_error)
  653. on_error();
  654. return;
  655. }
  656. var after_cancel = function(r) {
  657. if(!r.exc) {
  658. frappe.utils.play_sound("cancel");
  659. me.refresh();
  660. callback && callback();
  661. me.script_manager.trigger("after_cancel");
  662. } else {
  663. on_error();
  664. }
  665. };
  666. frappe.ui.form.save(me, "cancel", after_cancel, btn);
  667. });
  668. }, on_error);
  669. };
  670. // delete the record
  671. _f.Frm.prototype.savetrash = function() {
  672. this.validate_form_action("Delete");
  673. frappe.model.delete_doc(this.doctype, this.docname, function(r) {
  674. window.history.back();
  675. });
  676. };
  677. _f.Frm.prototype.amend_doc = function() {
  678. if(!this.fields_dict['amended_from']) {
  679. alert('"amended_from" field must be present to do an amendment.');
  680. return;
  681. }
  682. this.validate_form_action("Amend");
  683. var me = this;
  684. var fn = function(newdoc) {
  685. newdoc.amended_from = me.docname;
  686. if(me.fields_dict && me.fields_dict['amendment_date'])
  687. newdoc.amendment_date = frappe.datetime.obj_to_str(new Date());
  688. };
  689. this.copy_doc(fn, 1);
  690. frappe.utils.play_sound("click");
  691. };
  692. _f.Frm.prototype.disable_save = function() {
  693. // IMPORTANT: this function should be called in refresh event
  694. this.save_disabled = true;
  695. this.toolbar.current_status = null;
  696. this.page.clear_primary_action();
  697. };
  698. _f.Frm.prototype.enable_save = function() {
  699. this.save_disabled = false;
  700. this.toolbar.set_primary_action();
  701. };
  702. _f.Frm.prototype.save_or_update = function() {
  703. if(this.save_disabled) return;
  704. if(this.doc.docstatus===0) {
  705. this.save();
  706. } else if(this.doc.docstatus===1 && this.doc.__unsaved) {
  707. this.save("Update");
  708. }
  709. };
  710. _f.Frm.prototype.dirty = function() {
  711. this.doc.__unsaved = 1;
  712. this.$wrapper.trigger('dirty');
  713. };
  714. _f.Frm.prototype.get_docinfo = function() {
  715. return frappe.model.docinfo[this.doctype][this.docname];
  716. };
  717. _f.Frm.prototype.is_dirty = function() {
  718. return this.doc.__unsaved;
  719. };
  720. _f.Frm.prototype.is_new = function() {
  721. return this.doc.__islocal;
  722. };
  723. _f.Frm.prototype.reload_docinfo = function(callback) {
  724. var me = this;
  725. frappe.call({
  726. method: "frappe.desk.form.load.get_docinfo",
  727. args: {
  728. doctype: me.doctype,
  729. name: me.doc.name
  730. },
  731. callback: function(r) {
  732. // docinfo will be synced
  733. if(callback) callback(r.docinfo);
  734. me.timeline.refresh();
  735. me.assign_to.refresh();
  736. me.attachments.refresh();
  737. }
  738. });
  739. };
  740. _f.Frm.prototype.get_perm = function(permlevel, access_type) {
  741. return this.perm[permlevel] ? this.perm[permlevel][access_type] : null;
  742. };
  743. _f.Frm.prototype.set_intro = function(txt, append) {
  744. this.dashboard.set_headline_alert(txt);
  745. //frappe.utils.set_intro(this, this.body, txt, append);
  746. };
  747. _f.Frm.prototype.set_footnote = function(txt) {
  748. this.footnote_area = frappe.utils.set_footnote(this.footnote_area, this.body, txt);
  749. };
  750. _f.Frm.prototype.add_custom_button = function(label, fn, group) {
  751. // temp! old parameter used to be icon
  752. if(group && group.indexOf("fa fa-")!==-1) group = null;
  753. var btn = this.page.add_inner_button(label, fn, group);
  754. this.custom_buttons[label] = btn;
  755. return btn;
  756. };
  757. _f.Frm.prototype.clear_custom_buttons = function() {
  758. this.page.clear_inner_toolbar();
  759. this.page.clear_user_actions();
  760. this.custom_buttons = {};
  761. };
  762. _f.Frm.prototype.add_fetch = function(link_field, src_field, tar_field) {
  763. if(!this.fetch_dict[link_field]) {
  764. this.fetch_dict[link_field] = {'columns':[], 'fields':[]};
  765. }
  766. this.fetch_dict[link_field].columns.push(src_field);
  767. this.fetch_dict[link_field].fields.push(tar_field);
  768. };
  769. _f.Frm.prototype.set_print_heading = function(txt) {
  770. this.pformat[this.docname] = txt;
  771. };
  772. _f.Frm.prototype.action_perm_type_map = {
  773. "Create": "create",
  774. "Save": "write",
  775. "Submit": "submit",
  776. "Update": "submit",
  777. "Cancel": "cancel",
  778. "Amend": "amend",
  779. "Delete": "delete"
  780. };
  781. _f.Frm.prototype.validate_form_action = function(action, resolve) {
  782. var perm_to_check = this.action_perm_type_map[action];
  783. var allowed_for_workflow = false;
  784. var perms = frappe.perm.get_perm(this.doc.doctype)[0];
  785. // Allow submit, write, cancel and create permissions for read only documents that are assigned by
  786. // workflows if the user already have those permissions. This is to allow for users to
  787. // continue through the workflow states and to allow execution of functions like Duplicate.
  788. if (frappe.workflow.is_read_only(this.doctype, this.docname) && (perms["write"] ||
  789. perms["create"] || perms["submit"] || perms["cancel"])) {
  790. var allowed_for_workflow = true;
  791. }
  792. if (!this.perm[0][perm_to_check] && !allowed_for_workflow) {
  793. if(resolve) {
  794. // re-enable buttons
  795. resolve();
  796. }
  797. frappe.throw (__("No permission to '{0}' {1}", [__(action), __(this.doc.doctype)]));
  798. }
  799. };
  800. _f.Frm.prototype.has_perm = function(ptype) {
  801. return frappe.perm.has_perm(this.doctype, 0, ptype, this.doc);
  802. };
  803. _f.Frm.prototype.scroll_to_element = function() {
  804. if (frappe.route_options && frappe.route_options.scroll_to) {
  805. var scroll_to = frappe.route_options.scroll_to;
  806. delete frappe.route_options.scroll_to;
  807. var selector = [];
  808. for (var key in scroll_to) {
  809. var value = scroll_to[key];
  810. selector.push(repl('[data-%(key)s="%(value)s"]', {key: key, value: value}));
  811. }
  812. selector = $(selector.join(" "));
  813. if (selector.length) {
  814. frappe.utils.scroll_to(selector);
  815. }
  816. }
  817. };