mc.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  1. window.top.currentMcUrl = '';
  2. window.top.addEventListener('popstate', function (event) {
  3. window.setTimeout(function () {
  4. hideMask();
  5. hideMoeFormMask();
  6. if (!event || (!event.state && event.state !== '')) {
  7. // console.error('ALIX No state!', event, event.state);
  8. return;
  9. }
  10. var state = event.state;
  11. if (state === '') state = '/';
  12. if (state[0] !== '/') state = '/' + state;
  13. if (!!state) fastLoad(state, false, true);
  14. }, 0);
  15. });
  16. $(document).ready(function () {
  17. var originalLocationPath = window.location.pathname;
  18. var params = window.location.search;
  19. // TODO make it so if param 'xy' is passed in, it doesn't go to parent
  20. var noMcStuffOnLoad = originalLocationPath.indexOf('notes') >= 0;
  21. if(!window.noMc){
  22. if (window.location.pathname === window.top.location.pathname) {
  23. window.top.location.href = '/mc' + window.location.pathname + window.location.search;
  24. return;
  25. }
  26. }
  27. if(window.noMc) return;
  28. // window.top.ensureRHS();
  29. $(document).on('click', '.stag_rhs_toggle', function () {
  30. var state = window.top.toggleRHS(),
  31. icon = $(this).find('i');
  32. if (state === 'collapsed') {
  33. icon.removeClass().addClass('fa fa-arrow-left');
  34. } else {
  35. icon.removeClass().addClass('fa fa-arrow-right');
  36. }
  37. });
  38. var body = $(window.top.document.body),
  39. icon = $('.stag_rhs_toggle i');
  40. if (body.is('.stag_rhs_collapsed')) {
  41. icon.removeClass().addClass('fa fa-arrow-left');
  42. }
  43. initCreateNote();
  44. initQuillEdit();
  45. initFastLoad();
  46. initPrimaryForm();
  47. initPatientPresenceIndicator();
  48. runMCInitializers();
  49. initFileInputs();
  50. // if(typeof initializeCalendar !== 'undefined') {
  51. // initializeCalendar();
  52. // }
  53. // if(typeof initIntakeEvents !== 'undefined') {
  54. // initIntakeEvents();
  55. // }
  56. // populate history on fresh load
  57. var target = window.top.location.pathname + window.top.location.search;
  58. if (target.indexOf('/mc') === 0) {
  59. target = target.split('/mc')[1];
  60. }
  61. if(noMcStuffOnLoad){
  62. target = originalLocationPath;
  63. }
  64. if(!window.noMc){
  65. fastLoad(target, true, false, true);
  66. }
  67. });
  68. function enableTimeSpecificFields(_checked, _valueClass, _rangeClass) {
  69. if (_valueClass) $('.' + _valueClass).prop('disabled', _checked);
  70. if (_rangeClass) $('.' + _rangeClass).prop('disabled', !_checked);
  71. }
  72. function toggleDisabledAsNeeded(_el, _targetValue, _enableClass, _disableClass) {
  73. if (_el.value === _targetValue) {
  74. if (_enableClass) $('.' + _enableClass).prop('disabled', false);
  75. if (_disableClass) $('.' + _disableClass).prop('disabled', true);
  76. }
  77. else {
  78. if (_enableClass) $('.' + _enableClass).prop('disabled', true);
  79. if (_disableClass) $('.' + _disableClass).prop('disabled', false);
  80. }
  81. }
  82. function toggleVisibilityAsNeeded(_el, _targetValue, _visibleClass, _hiddenClass) {
  83. if (_el.value === _targetValue) {
  84. if (_visibleClass) $('.' + _visibleClass).removeClass('d-none');
  85. if (_hiddenClass) $('.' + _hiddenClass).addClass('d-none');
  86. }
  87. else {
  88. if (_visibleClass) $('.' + _visibleClass).addClass('d-none');
  89. if (_hiddenClass) $('.' + _hiddenClass).removeClass('d-none');
  90. }
  91. }
  92. var fastCache = {};
  93. function initFastLoad(_parent = false) {
  94. var allAs = $('a[href]:not([onclick]):not([href="#"]):not([native]):not([open-in-stag-popup])');
  95. if (_parent) {
  96. allAs = _parent.find('a[href]:not([onclick]):not([href="#"]):not([native]):not([open-in-stag-popup])');
  97. }
  98. // clear cache
  99. if (!_parent) {
  100. fastCache = {};
  101. }
  102. else {
  103. allAs.each(function () {
  104. if (typeof fastCache[this.href] !== 'undefined') {
  105. delete fastCache[this.href];
  106. }
  107. });
  108. }
  109. // find links without event handlers
  110. allAs.each(function () {
  111. if (!$(this).closest('[moe]').length) {
  112. if ($(this).closest('.dropdown-menu').length) {
  113. enableFastLoad(this, true);
  114. } else {
  115. // var handlers = findEventHandlers('click', this);
  116. // if (!handlers || !handlers.length) {
  117. enableFastLoad(this);
  118. // }
  119. }
  120. }
  121. });
  122. function enableFastLoad(_a, _menuItem = false) {
  123. $(_a)
  124. .off('click.fast-load')
  125. .on('click.fast-load', function () {
  126. fastLoad(this.href, true, true);
  127. $('.dropdown-menu')
  128. .removeClass('show')
  129. .prev('.dropdown-toggle').attr('aria-expanded', 'false');
  130. return false;
  131. });
  132. // console.info('FastLoad enabled for ' + _a.innerText + ' [' + _a.href + ']');
  133. }
  134. // fast cache
  135. // allAs = $('a[href]:not([onclick]):not([href="#"])');
  136. // allAs.each(function () {
  137. // var a = this;
  138. // $.get(a.href, function (_data) {
  139. // fastCache[a.href] = _data;
  140. // });
  141. // });
  142. }
  143. function onFastLoaded(_data, _href, _history, _target = null) {
  144. if (!Number.isInteger(_data)) {
  145. _data = '<div>' + _data + '</div>';
  146. // do for each element in _target
  147. let responseError = false;
  148. let originalTarget = _target;
  149. _target = _target ? _target : '.stag-content';
  150. _target = _target.split(',').map(_x => $.trim(_x));
  151. for (let i = 0; i < _target.length; i++) {
  152. let t = _target[i];
  153. let targetElement = $(t).first();
  154. if(targetElement.length) {
  155. let sourceElement = $(_data).find(t).first();
  156. if (sourceElement && sourceElement.length) {
  157. targetElement.html(sourceElement.html());
  158. initFastLoad(targetElement);
  159. console.log('ALIX loaded element: ' + t);
  160. }
  161. else {
  162. responseError = true;
  163. }
  164. }
  165. else {
  166. responseError = true;
  167. }
  168. }
  169. if (!responseError) {
  170. hideMask();
  171. hideMoeFormMask();
  172. window.setTimeout(function () {
  173. initCreateNote();
  174. initQuillEdit();
  175. initPrimaryForm();
  176. initPatientPresenceIndicator();
  177. initFileInputs();
  178. initMoes();
  179. runMCInitializers(originalTarget);
  180. if (window.top.currentMcUrl.split('?')[0] !== window.top.location.href.split('?')[0]) {
  181. $(window).scrollTop(0);
  182. }
  183. window.top.currentMcUrl = window.top.location.href;
  184. }, 0);
  185. }
  186. else {
  187. $('.stag-content').first().html('<p class="text-danger p-3 small">Error on page: <b>' + _href + '</b></p>');
  188. hideMask();
  189. hideMoeFormMask();
  190. }
  191. appendRedirectUrl();
  192. } else {
  193. // fallback
  194. let msg = 'Unable to open page: ';
  195. switch (_data) {
  196. case 403:
  197. msg = 'You do not have access to this page: ';
  198. break;
  199. case 404:
  200. msg = 'Page not found: ';
  201. break;
  202. case 500:
  203. msg = 'Error on page: ';
  204. break;
  205. case 0: // not logged in - refresh top level window to go to login
  206. window.top.location = '/';
  207. break;
  208. }
  209. console.warn('MC: Target page failed: ' + _href);
  210. $('.stag-content').first().html('<p class="text-danger p-3 small"><b>' + _data + '</b> - ' + msg + '<b>' + _href + '</b></p>');
  211. hideMask();
  212. hideMoeFormMask();
  213. appendRedirectUrl();
  214. }
  215. $('html, body').removeClass('no-scroll');
  216. }
  217. function appendRedirectUrl(_url) {
  218. let targetLocation = window.top.location.pathname + window.top.location.search;
  219. if(targetLocation.indexOf('/mc') === 0) {
  220. targetLocation = targetLocation.substr(3);
  221. }
  222. let form = $('.frm-back-to-admin');
  223. if(form.length) {
  224. form.attr('action', form.attr('data-action') + '?redir=' + targetLocation);
  225. }
  226. }
  227. var fastReload = function(_target = null) {
  228. var targetLocation = window.top.location.pathname + window.top.location.search;
  229. if(targetLocation.indexOf('/mc') === 0) {
  230. targetLocation = targetLocation.substr(3);
  231. }
  232. if(targetLocation === '' || targetLocation[0] !== '/') targetLocation = '/' + targetLocation;
  233. fastLoad(targetLocation, false, false, false, _target);
  234. return false;
  235. }
  236. function fastLoad(_href, _history = true, _useCache = true, _replaceState = false, _target = null) {
  237. let domPro = $(window.top.document.body).attr('data-pro-uid'),
  238. lsPro = window.top.localStorage.currentProUid;
  239. if(lsPro && domPro && lsPro !== domPro) {
  240. console.warn('ALIX Looks like you have a session as another pro on another tab. Refreshing window.top...');
  241. window.top.location.href = _href;
  242. return false;
  243. }
  244. showMask();
  245. if (_href === '') _href = '/';
  246. // push state
  247. if (_history && window.parent === window.top) {
  248. var target = _href;
  249. if (target.indexOf('//') !== -1) {
  250. target = target.split('//')[1];
  251. if (target.indexOf('/') !== -1) {
  252. target = target.substr(target.indexOf('/') + 1);
  253. }
  254. }
  255. if (target[0] === '/') target = target.substr(1);
  256. if (_replaceState) {
  257. window.top.history.replaceState(target, null, '/mc/' + target);
  258. }
  259. else {
  260. window.top.history.pushState(target, null, '/mc/' + target);
  261. }
  262. }
  263. // dont show top nav if in iframe
  264. if(window !== window.top && window.parent !== window.top) {
  265. $('body').addClass('in-iframe');
  266. }
  267. if (_useCache && !!fastCache[_href]) {
  268. onFastLoaded(fastCache[_href], _href, _history, _target);
  269. } else {
  270. let cleanedHREF = _href;
  271. if(cleanedHREF.length > 1 && cleanedHREF[cleanedHREF.length - 1] === '/') {
  272. cleanedHREF = cleanedHREF.substr(0, cleanedHREF.length - 1);
  273. }
  274. if(cleanedHREF.length > 2) {
  275. cleanedHREF = cleanedHREF.replace('/?', '?');
  276. }
  277. if(cleanedHREF.length > 0 && cleanedHREF[0] === '?') cleanedHREF = '/' + cleanedHREF;
  278. $.get(cleanedHREF, function (_data) {
  279. onFastLoaded(_data, _href, _history, _target);
  280. }).fail(function (_jqXhr) {
  281. onFastLoaded(_jqXhr.status, _href, _history, _target);
  282. });
  283. }
  284. }
  285. function initPrimaryForm(_form = false) {
  286. var primaryForm = _form ? _form : $('.primary-form:visible');
  287. if (primaryForm.length) {
  288. primaryForm = primaryForm.first();
  289. var rte = primaryForm.find('[contenteditable="true"]').first();
  290. if (rte.length) {
  291. rte.focus().select();
  292. }
  293. else {
  294. if (primaryForm.find('[autofocus]:visible').length) {
  295. primaryForm.find('[autofocus]:visible').first().focus().select();
  296. }
  297. else {
  298. primaryForm.find('input:not([type="hidden"]):visible, textarea:visible, select:visible').first().focus().select();
  299. }
  300. }
  301. }
  302. }
  303. function openInRHS(_url) {
  304. window.top.showRHS();
  305. var icon = $('.stag_rhs_toggle i');
  306. icon.removeClass().addClass('fa fa-arrow-right');
  307. window.top.openInRHS(_url);
  308. return false;
  309. }
  310. function initCreateNote() {
  311. $(document)
  312. .off('click.create-note', '.create-auto-note-trigger')
  313. .on('click.create-note', '.create-auto-note-trigger', function () {
  314. createNewNote($(this).attr('data-patient-uid'), $(this).attr('data-hcp-uid'), $(this).attr('data-effective-date'));
  315. });
  316. if ($('select[name="hasMcpDoneOnboardingVisit"]').length) {
  317. $('select[name="hasMcpDoneOnboardingVisit"]').trigger('change');
  318. }
  319. }
  320. function createNewNote(_patientUid, _hcpUid, _date) {
  321. hideMoeFormMask();
  322. showMask();
  323. $.post('/api/note/createUsingFreeTextHtml', {
  324. clientUid: _patientUid,
  325. hcpProUid: _hcpUid,
  326. effectiveDateEST: _date,
  327. }, function (_data) {
  328. hideMask();
  329. if (!_data.success) {
  330. toastr.error(_data.message);
  331. }
  332. else {
  333. fastLoad('/patients/view/' + _patientUid + '/notes/view/' + _data.data, true, false);
  334. }
  335. }, 'json');
  336. }
  337. function initQuillEdit(_selector = '.note-content[auto-edit]') {
  338. $(document)
  339. .off('click.enable-edit', '.note-content:not([auto-edit]):not(.readonly)')
  340. .on('click.enable-edit', '.note-content:not([auto-edit]):not(.readonly)', function () {
  341. $(this).attr('auto-edit', 1);
  342. initQuillEdit();
  343. initPrimaryForm();
  344. initPatientPresenceIndicator();
  345. });
  346. if (!$(_selector).length) return;
  347. var noteUid = $(_selector).attr('data-note-uid');
  348. var qe = new Quill(_selector, {
  349. theme: 'snow',
  350. modules: stagQuillConfig
  351. });
  352. var toolbar = $(qe.container).prev('.ql-toolbar');
  353. var saveButton = $('<button class="btn btn-sm btn-primary w-auto px-3 py-0 text-sm text-white save-note-content">Save</button>');
  354. toolbar.append(saveButton);
  355. saveButton.on('click', function () {
  356. $.post('/api/note/putFreeTextHtml', {
  357. uid: noteUid,
  358. freeTextHtml: qe.root.innerHTML,
  359. }, function (_data) {
  360. if (!_data.success) {
  361. toastr.error(_data.message);
  362. }
  363. else {
  364. // toastr.success('Note saved');
  365. // saveButton.prop('disabled', true);
  366. fastLoad(window.top.location.pathname.substr(3), false, false);
  367. }
  368. }, 'json');
  369. });
  370. // give a unique id to this editor instance
  371. var editorID = Math.ceil(Math.random() * 99999);
  372. // add button for new shortcut
  373. var newSCButton = $('<button class="btn btn-sm btn-default w-auto px-2 ml-2 border py-0 ' +
  374. 'text-sm add-shortcut" data-editor-id="' + editorID + '">+ Shortcut</button>');
  375. toolbar.append(newSCButton);
  376. // qe.on('text-change', function() {
  377. // saveButton.prop('disabled', false);
  378. // });
  379. $('.ql-editor[contenteditable]')
  380. .attr('data-editor-id', editorID)
  381. .attr('with-shortcuts', 1);
  382. }
  383. function initQuillRTE(_selector, _config = false, _shortcuts = false) {
  384. if(!_config) _config = stagQuillConfig;
  385. $(_selector).each(function() {
  386. $(this).wrap(
  387. $('<div class="border-left border-right rte-holder"/>')
  388. .attr('data-shortcuts', '')
  389. );
  390. // give a unique id to this editor instance
  391. var editorID = Math.ceil(Math.random() * 99999),
  392. fieldName = this.name;
  393. var ti = $('<input type="hidden" />')
  394. .val(this.value)
  395. .attr('name', this.name)
  396. .insertBefore(this);
  397. var ce = $('<div data-editor-id="' + editorID + '" data-field="' + this.name + '"/>')
  398. .html(this.value)
  399. .insertBefore(this);
  400. $(this).remove();
  401. var qe = new Quill('[data-editor-id="' + editorID + '"]', {
  402. theme: 'snow',
  403. modules: _config ? _config : stagQuillConfig
  404. });
  405. var toolbar = $(qe.container).prev('.ql-toolbar');
  406. // add button for new shortcut
  407. if(_shortcuts) {
  408. var newSCButton = $('<button class="btn bg-white btn-sm btn-default text-primary w-auto px-2 border py-0 ' +
  409. 'text-sm add-shortcut" data-editor-id="' + editorID + '">+ Shortcut</button>');
  410. toolbar.append(newSCButton);
  411. }
  412. qe.on('text-change', function() {
  413. ti.val(qe.root.innerHTML);
  414. });
  415. $(qe.container)
  416. .find('.ql-editor[contenteditable]')
  417. .attr('data-field', fieldName)
  418. .attr('data-editor-id', editorID)
  419. .attr('with-shortcuts', 1);
  420. });
  421. }
  422. var patientPresenceTimer = false;
  423. function initFileInputs() {
  424. $(document)
  425. .off('change', 'input[type="file"]')
  426. .on('change', 'input[type="file"]', function(_e) {
  427. if(_e.target.files && _e.target.files.length) {
  428. $(this).attr('selected-file', _e.target.files[0].name);
  429. }
  430. else {
  431. $(this).attr('selected-file', 'No file chosen');
  432. }
  433. return false;
  434. });
  435. $('input[type="file"]').attr('selected-file', 'No file chosen');
  436. }
  437. function initPatientPresenceIndicator() {
  438. return false;
  439. if (patientPresenceTimer !== false) {
  440. window.clearInterval(patientPresenceTimer);
  441. patientPresenceTimer = false;
  442. console.log('Cancelled previous timer!');
  443. }
  444. var elem = $('.patient-presence-indicator[data-patient-uid]');
  445. if (elem.length) {
  446. var patientUid = elem.attr('data-patient-uid');
  447. patientPresenceTimer = window.setInterval(function () {
  448. var elem = $('.patient-presence-indicator[data-patient-uid]');
  449. if (elem.length) {
  450. var patientUid = elem.attr('data-patient-uid');
  451. $.get('/patients/' + patientUid + '/presence', function (_data) {
  452. if (_data.online) {
  453. elem.addClass('online');
  454. }
  455. else {
  456. elem.removeClass('online');
  457. }
  458. }, 'json');
  459. }
  460. }, 15000); // once in 15 seconds
  461. }
  462. }
  463. // not really the place for this!
  464. // find a better place to put this
  465. window.fillJsonDataField = function(form, field = "data") {
  466. // add [data-name] values to payload
  467. if(form.is('[data-field-name]')) {
  468. field = form.attr('data-field-name');
  469. }
  470. let dataField = form.find('[name="' + field + '"]').first();
  471. let parsed = null;
  472. if(dataField.val()) {
  473. parsed = JSON.parse(dataField.val());
  474. }
  475. form.find('[data-name]').each(function() {
  476. if(!parsed) parsed = {};
  477. let keys = $(this).attr('data-name').split('->');
  478. let currentNode = parsed;
  479. for (let i = 0; i < keys.length; i++) {
  480. if(i !== keys.length - 1) {
  481. if(typeof currentNode[keys[i]] === 'undefined') {
  482. currentNode[keys[i]] = {};
  483. }
  484. currentNode = currentNode[keys[i]];
  485. }
  486. else {
  487. if($(this).is(':radio')) {
  488. if($(this).prop('checked')) {
  489. currentNode[keys[i]] = this.value;
  490. }
  491. }
  492. else if($(this).is(':checkbox')) {
  493. currentNode[keys[i]] = $(this).prop('checked');
  494. }
  495. else {
  496. currentNode[keys[i]] = $(this).val();
  497. }
  498. }
  499. }
  500. });
  501. if(parsed) {
  502. dataField.val(JSON.stringify(parsed));
  503. }
  504. return parsed;
  505. }
  506. window.refreshSegment = function(_segment) {
  507. $('.visit-segment[data-segment-template-name="' + _segment + '"]').find('.refresh-segment').trigger('click');
  508. };
  509. window.refreshAffectedSegmentsByType = function(_type) {
  510. if(!_type) {
  511. console.error('refreshAffectedSegmentsByType: _type cannot be empty!');
  512. return;
  513. }
  514. let segments = window.segmentRefreshConfig.typeToSegments[_type];
  515. if(segments && segments.length) {
  516. for (let i = 0; i < segments.length; i++) {
  517. refreshSegment(segments[i]);
  518. }
  519. }
  520. else {
  521. if(!_type) {
  522. console.error('refreshAffectedSegmentsByType: no segments to refresh for type:', _type);
  523. }
  524. }
  525. };
  526. window.refreshAffectedSegmentsByPopupKey = function(_key) {
  527. let types = [];
  528. for(let x in window.segmentRefreshConfig.wizardToTypes) {
  529. if(window.segmentRefreshConfig.wizardToTypes.hasOwnProperty(x) && _key.indexOf(x) !== -1) {
  530. types.push(window.segmentRefreshConfig.wizardToTypes[x]);
  531. break;
  532. }
  533. }
  534. for (let i = 0; i < types.length; i++) {
  535. refreshAffectedSegmentsByType(types[i]);
  536. }
  537. let segments = [];
  538. for(let x in window.segmentRefreshConfig.wizardToSegments) {
  539. if(window.segmentRefreshConfig.wizardToSegments.hasOwnProperty(x) && _key.indexOf(x) !== -1) {
  540. segments = window.segmentRefreshConfig.wizardToSegments[x];
  541. break;
  542. }
  543. }
  544. for (let i = 0; i < segments.length; i++) {
  545. refreshSegment(segments[i]);
  546. }
  547. };
  548. window.saveVisitForm = function(_trigger, _silent = false, _close = false, _doneCallback = null) {
  549. console.info("saveVisitForm");
  550. let form = $(_trigger).closest('form');
  551. if (!_silent && !form[0].checkValidity()) {
  552. form[0].reportValidity();
  553. return false;
  554. }
  555. let parsed = fillJsonDataField(form);
  556. let closeOnSave = false, noteSection = form.closest('.note-section');
  557. if($(_trigger).closest('[visit-moe]').is('[close-on-save]')) {
  558. closeOnSave = true;
  559. }
  560. // disallow-if-value-same-as
  561. let compareWith = false;
  562. if(form.find('.disallow-if-value-same-as')) {
  563. compareWith = $.trim(form.find('.disallow-if-value-same-as').text());
  564. if(compareWith && parsed) {
  565. if(!parsed.value) {
  566. alert('Value cannot be empty!');
  567. return false;
  568. }
  569. let newValue = $('<div/>').html(parsed.value).text().replace(/[^a-zA-Z0-9]/g, '');
  570. if(newValue === '') {
  571. alert('Value cannot be empty!');
  572. return false;
  573. }
  574. if(newValue === compareWith) {
  575. alert('New value should be different from the previous value!');
  576. return false;
  577. }
  578. }
  579. }
  580. if(!_silent) showMask();
  581. $.post(form.attr('url'), form.serialize(), _data => {
  582. if(!hasResponseError(_data)) {
  583. if(typeof window.updateAllSegmentsInResponse !== 'undefined') {
  584. window.updateAllSegmentsInResponse(_data, true, _silent);
  585. }
  586. let parentPopup = form.closest('.stag-popup');
  587. let eps = [
  588. '/api/visitPoint/upsertChildReview',
  589. '/api/visitPoint/upsertChildPlan',
  590. '/api/visitPoint/destroyCurrentChildReview',
  591. '/api/visitPoint/destroyCurrentChildPlan',
  592. '/api/visitPoint/addTopLevelBulkPreExisting'
  593. ];
  594. if(parentPopup.length && eps.indexOf(form.attr('url')) !== -1) {
  595. refreshAffectedSegmentsByPopupKey(parentPopup.attr('stag-popup-key'));
  596. }
  597. if(typeof window.refreshRHSSidebar !== 'undefined') {
  598. window.refreshRHSSidebar();
  599. }
  600. if(!_silent) {
  601. hideMask();
  602. if(noteSection.length) {
  603. if (closeOnSave) {
  604. noteSection.removeClass('edit');
  605. let segmentUid = form.find('[name="segmentUid"]').first();
  606. segmentUid = segmentUid.length ? segmentUid.val() : false;
  607. if (segmentUid) {
  608. window.setTimeout(() => {
  609. $('.note-tree-node>a[data-segment-uid="' + segmentUid + '"]').trigger('click');
  610. }, 250);
  611. }
  612. }
  613. }
  614. if($(_trigger).closest('[visit-moe]').closest('.stag-popup').length) {
  615. refreshDynamicStagPopup();
  616. }
  617. }
  618. if(_close) {
  619. closeStagPopup();
  620. }
  621. if(!!_doneCallback) {
  622. _doneCallback();
  623. }
  624. }
  625. }, 'json');
  626. return false;
  627. };
  628. window.initSegmentMoes = function(_parent) {
  629. $('body')
  630. .off('mousedown.visit-moe-outside-click')
  631. .on('mousedown.visit-moe-outside-click', function (e) {
  632. if ($(e.target).closest('[visit-moe]').length ||
  633. $(e.target).closest('#create-shortcut-form').length ||
  634. $(e.target).is('#create-shortcut-form') ||
  635. $(e.target).is('.stag-shortcuts .sc') ||
  636. $(e.target).closest('.ui-datepicker').length) {
  637. return;
  638. }
  639. $('[visit-moe] [url]:not([show])').hide();
  640. });
  641. _parent.find('[visit-moe] [submit]')
  642. .off('click.visit-moe-submit')
  643. .on('click.visit-moe-submit', function() {
  644. saveVisitForm(this);
  645. return false;
  646. });
  647. _parent.find('[visit-moe]>a[start]')
  648. .off('click.visit-moe-show')
  649. .on('click.visit-moe-show', function () {
  650. $('[visit-moe] [url]:not([show])').hide();
  651. let form = $(this).closest('[visit-moe]').find('form[url]');
  652. form.show();
  653. if(!form.is('[no-auto-focus]')) {
  654. setTimeout(() => {
  655. form.find('.ql-editor').first().focus();
  656. }, 0);
  657. }
  658. return false;
  659. });
  660. _parent.find('[visit-moe] [cancel]')
  661. .off('click.visit-moe-cancel')
  662. .on('click.visit-moe-cancel', function() {
  663. $(this).closest('[visit-moe]').find('[url]:not([show])').hide();
  664. if($(this).closest('[visit-moe]').is('[close-on-cancel]')) {
  665. $(this).closest('.note-section').removeClass('edit');
  666. }
  667. return false;
  668. });
  669. $(document)
  670. .off('keydown.visit-moe-escape')
  671. .on('keydown.visit-moe-escape', function (e) {
  672. if(e.which === 27) {
  673. if(!isEventConsumed(e)) {
  674. let visibleMoes = $('[visit-moe] [url]:not([show]):visible');
  675. if (visibleMoes.length) {
  676. visibleMoes.hide();
  677. markEventAsConsumed(e);
  678. return false;
  679. }
  680. }
  681. }
  682. });
  683. };
  684. window.isEventConsumed = function(_e) {
  685. return _e && _e.originalEvent && _e.originalEvent.stagCosumed
  686. };
  687. window.markEventAsConsumed = function(_e) {
  688. if(_e && _e.originalEvent) {
  689. _e.originalEvent.stagCosumed = true;
  690. }
  691. };