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.
 
 
 
 
 
 

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