mc.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  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])');
  95. if (_parent) {
  96. allAs = _parent.find('a[href]:not([onclick]):not([href="#"]):not([native])');
  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[aria-labelledby="practice-management"]').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[aria-labelledby="practice-management"]')
  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. _target = _target ? _target : '.stag-content';
  149. _target = _target.split(',').map(_x => $.trim(_x));
  150. for (let i = 0; i < _target.length; i++) {
  151. let t = _target[i];
  152. let targetElement = $(t).first();
  153. if(targetElement.length) {
  154. let sourceElement = $(_data).find(t).first();
  155. if (sourceElement && sourceElement.length) {
  156. targetElement.html(sourceElement.html());
  157. initFastLoad(targetElement);
  158. console.log('ALIX loaded element: ' + t);
  159. }
  160. else {
  161. responseError = true;
  162. }
  163. }
  164. else {
  165. responseError = true;
  166. }
  167. }
  168. if (!responseError) {
  169. hideMask();
  170. hideMoeFormMask();
  171. window.setTimeout(function () {
  172. initCreateNote();
  173. initQuillEdit();
  174. initPrimaryForm();
  175. initPatientPresenceIndicator();
  176. runMCInitializers();
  177. initFileInputs();
  178. initMoes();
  179. if (window.top.currentMcUrl.split('?')[0] !== window.top.location.href.split('?')[0]) {
  180. $(window).scrollTop(0);
  181. }
  182. window.top.currentMcUrl = window.top.location.href;
  183. }, 0);
  184. }
  185. else {
  186. $('.stag-content').first().html('<p class="text-danger p-3 small">Error on page: <b>' + _href + '</b></p>');
  187. hideMask();
  188. hideMoeFormMask();
  189. }
  190. } else {
  191. // fallback
  192. let msg = 'Unable to open page: ';
  193. switch (_data) {
  194. case 403:
  195. msg = 'You do not have access to this page: ';
  196. break;
  197. case 404:
  198. msg = 'Page not found: ';
  199. break;
  200. case 500:
  201. msg = 'Error on page: ';
  202. break;
  203. case 0: // not logged in - refresh top level window to go to login
  204. window.top.location = '/';
  205. break;
  206. }
  207. console.warn('MC: Target page failed: ' + _href);
  208. $('.stag-content').first().html('<p class="text-danger p-3 small"><b>' + _data + '</b> - ' + msg + '<b>' + _href + '</b></p>');
  209. hideMask();
  210. hideMoeFormMask();
  211. }
  212. $('html, body').removeClass('no-scroll');
  213. }
  214. var fastReload = function(_target = null) {
  215. var targetLocation = window.top.location.pathname + window.top.location.search;
  216. if(targetLocation.indexOf('/mc') === 0) {
  217. targetLocation = targetLocation.substr(3);
  218. }
  219. if(targetLocation === '' || targetLocation[0] !== '/') targetLocation = '/' + targetLocation;
  220. fastLoad(targetLocation, false, false, false, _target);
  221. return false;
  222. }
  223. function fastLoad(_href, _history = true, _useCache = true, _replaceState = false, _target = null) {
  224. let domPro = $(window.top.document.body).attr('data-pro-uid'),
  225. lsPro = window.top.localStorage.currentProUid;
  226. if(lsPro && domPro && lsPro !== domPro) {
  227. console.warn('ALIX Looks like you have a session as another pro on another tab. Refreshing window.top...');
  228. window.top.location.href = _href;
  229. return false;
  230. }
  231. showMask();
  232. if (_href === '') _href = '/';
  233. // push state
  234. if (_history && window.parent === window.top) {
  235. var target = _href;
  236. if (target.indexOf('//') !== -1) {
  237. target = target.split('//')[1];
  238. if (target.indexOf('/') !== -1) {
  239. target = target.substr(target.indexOf('/') + 1);
  240. }
  241. }
  242. if (target[0] === '/') target = target.substr(1);
  243. if (_replaceState) {
  244. window.top.history.replaceState(target, null, '/mc/' + target);
  245. }
  246. else {
  247. window.top.history.pushState(target, null, '/mc/' + target);
  248. }
  249. }
  250. // dont show top nav if in iframe
  251. if(window !== window.top && window.parent !== window.top) {
  252. $('body').addClass('in-iframe');
  253. }
  254. if (_useCache && !!fastCache[_href]) {
  255. onFastLoaded(fastCache[_href], _href, _history, _target);
  256. } else {
  257. let cleanedHREF = _href;
  258. if(cleanedHREF.length > 1 && cleanedHREF[cleanedHREF.length - 1] === '/') {
  259. cleanedHREF = cleanedHREF.substr(0, cleanedHREF.length - 1);
  260. }
  261. if(cleanedHREF.length > 2) {
  262. cleanedHREF = cleanedHREF.replace('/?', '?');
  263. }
  264. if(cleanedHREF.length > 0 && cleanedHREF[0] === '?') cleanedHREF = '/' + cleanedHREF;
  265. $.get(cleanedHREF, function (_data) {
  266. onFastLoaded(_data, _href, _history, _target);
  267. }).fail(function (_jqXhr) {
  268. onFastLoaded(_jqXhr.status, _href, _history, _target);
  269. });
  270. }
  271. }
  272. function initPrimaryForm(_form = false) {
  273. var primaryForm = _form ? _form : $('.primary-form:visible');
  274. if (primaryForm.length) {
  275. primaryForm = primaryForm.first();
  276. var rte = primaryForm.find('[contenteditable="true"]').first();
  277. if (rte.length) {
  278. rte.focus().select();
  279. }
  280. else {
  281. if (primaryForm.find('[autofocus]:visible').length) {
  282. primaryForm.find('[autofocus]:visible').first().focus().select();
  283. }
  284. else {
  285. primaryForm.find('input:not([type="hidden"]):visible, textarea:visible, select:visible').first().focus().select();
  286. }
  287. }
  288. }
  289. }
  290. function openInRHS(_url) {
  291. window.top.showRHS();
  292. var icon = $('.stag_rhs_toggle i');
  293. icon.removeClass().addClass('fa fa-arrow-right');
  294. window.top.openInRHS(_url);
  295. return false;
  296. }
  297. function initCreateNote() {
  298. $(document)
  299. .off('click.create-note', '.create-auto-note-trigger')
  300. .on('click.create-note', '.create-auto-note-trigger', function () {
  301. createNewNote($(this).attr('data-patient-uid'), $(this).attr('data-hcp-uid'), $(this).attr('data-effective-date'));
  302. });
  303. if ($('select[name="hasMcpDoneOnboardingVisit"]').length) {
  304. $('select[name="hasMcpDoneOnboardingVisit"]').trigger('change');
  305. }
  306. }
  307. function createNewNote(_patientUid, _hcpUid, _date) {
  308. hideMoeFormMask();
  309. showMask();
  310. $.post('/api/note/createUsingFreeTextHtml', {
  311. clientUid: _patientUid,
  312. hcpProUid: _hcpUid,
  313. effectiveDateEST: _date,
  314. }, function (_data) {
  315. hideMask();
  316. if (!_data.success) {
  317. toastr.error(_data.message);
  318. }
  319. else {
  320. fastLoad('/patients/view/' + _patientUid + '/notes/view/' + _data.data, true, false);
  321. }
  322. }, 'json');
  323. }
  324. function initQuillEdit(_selector = '.note-content[auto-edit]') {
  325. $(document)
  326. .off('click.enable-edit', '.note-content:not([auto-edit]):not(.readonly)')
  327. .on('click.enable-edit', '.note-content:not([auto-edit]):not(.readonly)', function () {
  328. $(this).attr('auto-edit', 1);
  329. initQuillEdit();
  330. initPrimaryForm();
  331. initPatientPresenceIndicator();
  332. });
  333. if (!$(_selector).length) return;
  334. var noteUid = $(_selector).attr('data-note-uid');
  335. var qe = new Quill(_selector, {
  336. theme: 'snow',
  337. modules: stagQuillConfig
  338. });
  339. var toolbar = $(qe.container).prev('.ql-toolbar');
  340. var saveButton = $('<button class="btn btn-sm btn-primary w-auto px-3 py-0 text-sm text-white save-note-content">Save</button>');
  341. toolbar.append(saveButton);
  342. saveButton.on('click', function () {
  343. $.post('/api/note/putFreeTextHtml', {
  344. uid: noteUid,
  345. freeTextHtml: qe.root.innerHTML,
  346. }, function (_data) {
  347. if (!_data.success) {
  348. toastr.error(_data.message);
  349. }
  350. else {
  351. // toastr.success('Note saved');
  352. // saveButton.prop('disabled', true);
  353. fastLoad(window.top.location.pathname.substr(3), false, false);
  354. }
  355. }, 'json');
  356. });
  357. // give a unique id to this editor instance
  358. var editorID = Math.ceil(Math.random() * 99999);
  359. // add button for new shortcut
  360. var newSCButton = $('<button class="btn btn-sm btn-default w-auto px-2 ml-2 border py-0 ' +
  361. 'text-sm add-shortcut" data-editor-id="' + editorID + '">+ Shortcut</button>');
  362. toolbar.append(newSCButton);
  363. // qe.on('text-change', function() {
  364. // saveButton.prop('disabled', false);
  365. // });
  366. $('.ql-editor[contenteditable]')
  367. .attr('data-editor-id', editorID)
  368. .attr('with-shortcuts', 1);
  369. }
  370. var patientPresenceTimer = false;
  371. function initFileInputs() {
  372. $(document)
  373. .off('change', 'input[type="file"]')
  374. .on('change', 'input[type="file"]', function(_e) {
  375. if(_e.target.files && _e.target.files.length) {
  376. $(this).attr('selected-file', _e.target.files[0].name);
  377. }
  378. else {
  379. $(this).attr('selected-file', 'No file chosen');
  380. }
  381. return false;
  382. });
  383. $('input[type="file"]').attr('selected-file', 'No file chosen');
  384. }
  385. function initPatientPresenceIndicator() {
  386. return false;
  387. if (patientPresenceTimer !== false) {
  388. window.clearInterval(patientPresenceTimer);
  389. patientPresenceTimer = false;
  390. console.log('Cancelled previous timer!');
  391. }
  392. var elem = $('.patient-presence-indicator[data-patient-uid]');
  393. if (elem.length) {
  394. var patientUid = elem.attr('data-patient-uid');
  395. patientPresenceTimer = window.setInterval(function () {
  396. var elem = $('.patient-presence-indicator[data-patient-uid]');
  397. if (elem.length) {
  398. var patientUid = elem.attr('data-patient-uid');
  399. $.get('/patients/' + patientUid + '/presence', function (_data) {
  400. if (_data.online) {
  401. elem.addClass('online');
  402. }
  403. else {
  404. elem.removeClass('online');
  405. }
  406. }, 'json');
  407. }
  408. }, 15000); // once in 15 seconds
  409. }
  410. }
  411. // not really the place for this!
  412. // find a better place to put this
  413. window.saveVisitForm = function(_trigger, _silent = false, _close = false, _doneCallback = null) {
  414. let form = $(_trigger).closest('form');
  415. if (!_silent && !form[0].checkValidity()) {
  416. form[0].reportValidity();
  417. return false;
  418. }
  419. // add [data-name] values to payload
  420. let dataField = form.find('[name="data"]').first();
  421. let parsed = null;
  422. if(dataField.val()) {
  423. parsed = JSON.parse(dataField.val());
  424. }
  425. form.find('[data-name]').each(function() {
  426. if(!parsed) parsed = {};
  427. let keys = $(this).attr('data-name').split('->');
  428. let currentNode = parsed;
  429. for (let i = 0; i < keys.length; i++) {
  430. if(i !== keys.length - 1) {
  431. if(typeof currentNode[keys[i]] === 'undefined') {
  432. currentNode[keys[i]] = {};
  433. }
  434. currentNode = currentNode[keys[i]];
  435. }
  436. else {
  437. if($(this).is(':checkbox')) {
  438. currentNode[keys[i]] = $(this).prop('checked');
  439. }
  440. else {
  441. currentNode[keys[i]] = $(this).val();
  442. }
  443. }
  444. }
  445. });
  446. if(parsed) {
  447. dataField.val(JSON.stringify(parsed));
  448. }
  449. let closeOnSave = false, noteSection = form.closest('.note-section');
  450. if($(_trigger).closest('[visit-moe]').is('[close-on-save]')) {
  451. closeOnSave = true;
  452. }
  453. // disallow-if-value-same-as
  454. let compareWith = false;
  455. if(form.find('.disallow-if-value-same-as')) {
  456. compareWith = $.trim(form.find('.disallow-if-value-same-as').text());
  457. if(compareWith && parsed) {
  458. if(!parsed.value) {
  459. alert('Value cannot be empty!');
  460. return false;
  461. }
  462. let newValue = $('<div/>').html(parsed.value).text().replace(/[^a-zA-Z0-9]/g, '');
  463. if(newValue === '') {
  464. alert('Value cannot be empty!');
  465. return false;
  466. }
  467. if(newValue === compareWith) {
  468. alert('New value should be different from the previous value!');
  469. return false;
  470. }
  471. }
  472. }
  473. if(!_silent) showMask();
  474. $.post(form.attr('url'), form.serialize(), _data => {
  475. if(!hasResponseError(_data)) {
  476. if(typeof window.updateAllSegmentsInResponse !== 'undefined' && noteSection.length) {
  477. window.updateAllSegmentsInResponse(_data, true, _silent);
  478. }
  479. if(typeof window.refreshRHSSidebar !== 'undefined') {
  480. window.refreshRHSSidebar();
  481. }
  482. if(!_silent) {
  483. hideMask();
  484. if(noteSection.length) {
  485. if (closeOnSave) {
  486. noteSection.removeClass('edit');
  487. let segmentUid = form.find('[name="segmentUid"]').first();
  488. segmentUid = segmentUid.length ? segmentUid.val() : false;
  489. if (segmentUid) {
  490. window.setTimeout(() => {
  491. $('.note-tree-node>a[data-segment-uid="' + segmentUid + '"]').trigger('click');
  492. }, 250);
  493. }
  494. }
  495. }
  496. if($(_trigger).closest('[visit-moe]').closest('.stag-popup').length) {
  497. refreshDynamicStagPopup();
  498. }
  499. }
  500. if(_close) {
  501. closeStagPopup();
  502. }
  503. if(!!_doneCallback) {
  504. _doneCallback();
  505. }
  506. }
  507. }, 'json');
  508. return false;
  509. };
  510. window.initSegmentMoes = function(_parent) {
  511. $('body')
  512. .off('mousedown.visit-moe-outside-click')
  513. .on('mousedown.visit-moe-outside-click', function (e) {
  514. if ($(e.target).closest('[visit-moe]').length ||
  515. $(e.target).closest('#create-shortcut-form').length ||
  516. $(e.target).is('#create-shortcut-form') ||
  517. $(e.target).is('.stag-shortcuts .sc') ||
  518. $(e.target).closest('.ui-datepicker').length) {
  519. return;
  520. }
  521. $('[visit-moe] [url]:not([show])').hide();
  522. });
  523. _parent.find('[visit-moe] [submit]')
  524. .off('click.visit-moe-submit')
  525. .on('click.visit-moe-submit', function() {
  526. saveVisitForm(this);
  527. return false;
  528. });
  529. _parent.find('[visit-moe]>a[start]')
  530. .off('click.visit-moe-show')
  531. .on('click.visit-moe-show', function () {
  532. $('[visit-moe] [url]:not([show])').hide();
  533. $(this)
  534. .closest('[visit-moe]')
  535. .find('form[url]')
  536. .show();
  537. return false;
  538. });
  539. _parent.find('[visit-moe] [cancel]')
  540. .off('click.visit-moe-cancel')
  541. .on('click.visit-moe-cancel', function() {
  542. $(this).closest('[visit-moe]').find('[url]:not([show])').hide();
  543. if($(this).closest('[visit-moe]').is('[close-on-cancel]')) {
  544. $(this).closest('.note-section').removeClass('edit');
  545. }
  546. return false;
  547. });
  548. $(document)
  549. .off('keydown.visit-moe-escape')
  550. .on('keydown.visit-moe-escape', function (e) {
  551. if(e.which === 27) {
  552. let visibleMoes = $('[visit-moe] [url]:not([show]):visible');
  553. if (visibleMoes.length) {
  554. visibleMoes.hide();
  555. markEventAsConsumed(e);
  556. return false;
  557. }
  558. }
  559. });
  560. };
  561. window.isEventConsumed = function(_e) {
  562. return _e && _e.originalEvent && _e.originalEvent.stagCosumed
  563. };
  564. window.markEventAsConsumed = function(_e) {
  565. if(_e && _e.originalEvent) {
  566. _e.originalEvent.stagCosumed = true;
  567. }
  568. };