mc.js 28 KB

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