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.
 
 
 
 
 
 

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