Pro.php 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366
  1. <?php
  2. namespace App\Models;
  3. # use Illuminate\Database\Eloquent\Model;
  4. use App\Helpers\TimeLine;
  5. use DateTime;
  6. use Exception;
  7. use Illuminate\Support\Facades\DB;
  8. class Pro extends Model
  9. {
  10. protected $table = 'pro';
  11. public function displayName($_flat = false) {
  12. $name = [];
  13. if(!empty($this->name_display)) return $this->name_display;
  14. $sep = ", ";
  15. if($_flat) {
  16. if(!empty($this->name_first)) $name[] = $this->name_first;
  17. if(!empty($this->name_last)) $name[] = $this->name_last;
  18. $sep = ' ';
  19. }
  20. else {
  21. if(!empty($this->name_last)) $name[] = $this->name_last;
  22. if(!empty($this->name_first)) $name[] = $this->name_first;
  23. }
  24. if(!count($name)) {
  25. $name = $this->name_display;
  26. }
  27. else {
  28. $name = implode($sep, $name);
  29. }
  30. return $name;
  31. }
  32. public function initials() {
  33. $characters = [];
  34. if(!empty($this->name_first)) $characters[] = $this->name_first[0];
  35. if(!empty($this->name_last)) $characters[] = $this->name_last[0];
  36. return strtolower(implode("", $characters));
  37. }
  38. public function debitBills()
  39. {
  40. return $this->hasMany(Bill::class, 'debit_pro_id');
  41. }
  42. public function cmBills()
  43. {
  44. return $this->hasMany(Bill::class, 'cm_pro_id');
  45. }
  46. public function hcpBills()
  47. {
  48. return $this->hasMany(Bill::class, 'hcp_pro_id');
  49. }
  50. public function teamsWhereMcp()
  51. {
  52. return $this->hasMany(ProTeam::class, 'mcp_pro_id', 'id');
  53. }
  54. public function teamsWhereAssistant()
  55. {
  56. return $this->hasMany(ProTeam::class, 'assistant_pro_id', 'id');
  57. }
  58. public function isDefaultNA()
  59. {
  60. return $this->is_considered_for_dna && !$this->is_hcp;
  61. }
  62. public function lastPayment() {
  63. return ProTransaction
  64. ::where('pro_id', $this->id)
  65. ->where('plus_or_minus', 'PLUS')
  66. ->orderBy('created_at', 'desc')
  67. ->first();
  68. }
  69. public function hasRates() {
  70. $numRates = ProRate::where('is_active', true)->where('pro_id', $this->id)->count();
  71. return $numRates > 0;
  72. }
  73. public function cmRates() {
  74. return ProRate::distinct('code')
  75. ->where('is_active', true)
  76. ->where('pro_id', $this->id)
  77. ->where('code', 'LIKE', 'CM%')
  78. ->get();
  79. }
  80. public function rmRates() {
  81. return ProRate::distinct('code')
  82. ->where('is_active', true)
  83. ->where('pro_id', $this->id)
  84. ->where('code', 'LIKE', 'RM%')
  85. ->get();
  86. }
  87. public function noteRates() {
  88. return ProRate::distinct('code')
  89. ->where('is_active', true)
  90. ->where('pro_id', $this->id)
  91. ->where('code', 'NOT LIKE', 'CM%')
  92. ->where('code', 'NOT LIKE', 'RM%')
  93. ->where('responsibility', '<>', 'GENERIC')
  94. ->where('responsibility', '<>', 'NA')
  95. ->get();
  96. }
  97. public function genericRates() {
  98. return ProRate::distinct('code')
  99. ->where('is_active', true)
  100. ->where('pro_id', $this->id)
  101. ->where('responsibility', 'GENERIC')
  102. ->get();
  103. }
  104. public function recentDebits() {
  105. return ProTransaction
  106. ::where('pro_id', $this->id)
  107. ->where('plus_or_minus', 'PLUS')
  108. ->orderBy('created_at', 'desc')
  109. ->skip(0)->take(4)->get();
  110. }
  111. public function shortcuts() {
  112. return $this->hasMany(ProTextShortcut::class, 'pro_id')->where('is_removed', false);
  113. }
  114. public function allShortcuts() {
  115. $myId = $this->id;
  116. $shortcuts = ProTextShortcut::where('is_removed', false)
  117. ->where(function ($query2) use ($myId) {
  118. $query2
  119. ->where('pro_id', $myId)
  120. ->orWhereNull('pro_id');
  121. })
  122. ->orderBy('shortcut')
  123. ->get();
  124. return $shortcuts;
  125. }
  126. public function noteTemplates() {
  127. return $this->hasMany(NoteTemplatePro::class, 'pro_id')
  128. ->where('is_removed', false)
  129. ->orderBy('position_index', 'asc');
  130. }
  131. public function visitTemplates() {
  132. if($this->pro_type == 'ADMIN'){
  133. return VisitTemplate::where('is_active' , true)->get();
  134. }
  135. $allAccessibleVisitTemplatesIDs = VisitTemplate::where('is_accessible_to_all', true)->where('is_active', true)->pluck('id')->toArray();
  136. $accesses = VisitTemplateAccess::where('pro_id', $this->id)->where('is_active', true)->pluck('visit_template_id')->toArray();
  137. $allAllowedVisitTemplatesIDs = array_unique(array_merge($allAccessibleVisitTemplatesIDs, $accesses));
  138. return VisitTemplate::whereIn('id', $allAllowedVisitTemplatesIDs)->get();
  139. }
  140. public function currentWork() {
  141. return ProClientWork::where('pro_id', $this->id)->where('is_active', true)->first();
  142. }
  143. public function isWorkingOnClient($_client) {
  144. $count = ProClientWork::where('pro_id', $this->id)->where('client_id', $_client->id)->where('is_active', true)->count();
  145. return $count > 0;
  146. }
  147. public function canvasCustomItems($_key) {
  148. return ClientCanvasDataCustomItem::where('key', $_key)
  149. ->where('pro_id', $this->id)
  150. ->where('is_removed', false)
  151. ->orderBy('label')
  152. ->get();
  153. }
  154. /**
  155. * @param $_start - YYYY-MM-DD
  156. * @param $_end - YYYY-MM-DD
  157. * @param string $_timezone - defaults to EASTERN
  158. * @param string $_availableBG - defaults to #00a
  159. * @param string $_unavailableBG - defaults to #a00
  160. * @return array
  161. * @throws Exception
  162. */
  163. public function getAvailabilityEvents($_start, $_end, $_timezone = 'EASTERN', $_availableBG = '#00a', $_unavailableBG = '#a00') {
  164. $_start .= ' 00:00:00';
  165. $_end .= ' 23:59:59';
  166. // get availability data
  167. $proGenAvail = ProGeneralAvailability
  168. ::where('is_cancelled', false)
  169. ->where('pro_id', $this->id)
  170. ->get();
  171. $proSpecAvail = ProSpecificAvailability
  172. ::where('is_cancelled', false)
  173. ->where('pro_id', $this->id)
  174. ->where(function ($query) use ($_start, $_end) {
  175. $query
  176. ->where(function ($query2) use ($_start, $_end) {
  177. $query2
  178. ->where('start_time', '>=', $_start)
  179. ->where('start_time', '<=', $_end);
  180. })
  181. ->orWhere(function ($query2) use ($_start, $_end) {
  182. $query2
  183. ->where('end_time', '>=', $_start)
  184. ->where('end_time', '<=', $_end);
  185. });
  186. })
  187. ->get();
  188. $proSpecUnavail = ProSpecificUnavailability
  189. ::where('is_cancelled', false)
  190. ->where('pro_id', $this->id)
  191. ->where(function ($query) use ($_start, $_end) {
  192. $query
  193. ->where(function ($query2) use ($_start, $_end) {
  194. $query2
  195. ->where('start_time', '>=', $_start)
  196. ->where('start_time', '<=', $_end);
  197. })
  198. ->orWhere(function ($query2) use ($_start, $_end) {
  199. $query2
  200. ->where('end_time', '>=', $_start)
  201. ->where('end_time', '<=', $_end);
  202. });
  203. })
  204. ->get();
  205. // default GA
  206. // if no gen avail, assume mon to fri, 9 to 7
  207. /*if (count($proGenAvail) === 0) {
  208. $dayNames = ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY'];
  209. foreach ($dayNames as $dayName) {
  210. $item = new \stdClass();
  211. $item->day_of_week = $dayName;
  212. $item->timezone = $_timezone;
  213. $item->start_time = '09:00:00';
  214. $item->end_time = '18:00:00';
  215. $proGenAvail->push($item);
  216. }
  217. }*/
  218. // create timeline
  219. $phpTZ = appTZtoPHPTZ($_timezone);
  220. $phpTZObject = new \DateTimeZone($phpTZ);
  221. $startDate = new \DateTime($_start, $phpTZObject);
  222. $endDate = new \DateTime($_end, $phpTZObject);
  223. $proTimeLine = new TimeLine($startDate, $endDate);
  224. // General availability
  225. $period = new \DatePeriod($startDate, \DateInterval::createFromDateString('1 day'), $endDate);
  226. $days = [];
  227. foreach ($period as $day) {
  228. $days[] = [
  229. "day" => strtoupper($day->format("l")), // SUNDAY, etc.
  230. "date" => $day->format("Y-m-d"), // 2020-10-04, etc.
  231. ];
  232. }
  233. foreach ($days as $day) {
  234. $proGenAvailForTheDay = $proGenAvail->filter(function ($record) use ($day) {
  235. return $record->day_of_week === $day["day"];
  236. });
  237. foreach ($proGenAvailForTheDay as $ga) {
  238. $gaStart = new \DateTime($day["date"], new \DateTimeZone(appTZtoPHPTZ($ga->timezone)));
  239. $parts = explode(":", $ga->start_time);
  240. $gaStart->setTime(intval($parts[0]), intval($parts[1]), intval($parts[2]));
  241. $gaStart->setTimezone($phpTZObject);
  242. $gaEnd = new \DateTime($day["date"], new \DateTimeZone(appTZtoPHPTZ($ga->timezone)));
  243. $parts = explode(":", $ga->end_time);
  244. $gaEnd->setTime(intval($parts[0]), intval($parts[1]), intval($parts[2]));
  245. $gaEnd->setTimezone($phpTZObject);
  246. $proTimeLine->addAvailability($gaStart, $gaEnd);
  247. }
  248. }
  249. // specific availability
  250. foreach ($proSpecAvail as $sa) {
  251. $saStart = new \DateTime($sa->start_time, new \DateTimeZone(appTZtoPHPTZ($sa->timezone)));
  252. $saStart->setTimezone($phpTZObject);
  253. $saEnd = new \DateTime($sa->end_time, new \DateTimeZone(appTZtoPHPTZ($sa->timezone)));
  254. $saEnd->setTimezone($phpTZObject);
  255. $proTimeLine->addAvailability($saStart, $saEnd);
  256. }
  257. // specific unavailability
  258. foreach ($proSpecUnavail as $sua) {
  259. $suaStart = new \DateTime($sua->start_time, new \DateTimeZone(appTZtoPHPTZ($sua->timezone)));
  260. $suaStart->setTimezone($phpTZObject);
  261. $suaEnd = new \DateTime($sua->end_time, new \DateTimeZone(appTZtoPHPTZ($sua->timezone)));
  262. $suaEnd->setTimezone($phpTZObject);
  263. $proTimeLine->removeAvailability($suaStart, $suaEnd);
  264. }
  265. $events = [];
  266. // availability
  267. foreach ($proTimeLine->getAvailable() as $item) {
  268. $eStart = new \DateTime('@' . $item->start);
  269. $eStart->setTimezone($phpTZObject);
  270. $eEnd = new \DateTime('@' . $item->end);
  271. $eEnd->setTimezone($phpTZObject);
  272. $events[] = [
  273. "type" => "availability",
  274. "start" => $eStart->format('Y-m-d H:i:s'),
  275. "end" => $eEnd->format('Y-m-d H:i:s'),
  276. "editable" => false,
  277. "backgroundColor" => $_availableBG
  278. ];
  279. }
  280. // unavailability
  281. foreach ($proTimeLine->getUnavailable() as $item) {
  282. $eStart = new \DateTime('@' . $item->start);
  283. $eStart->setTimezone($phpTZObject);
  284. $eEnd = new \DateTime('@' . $item->end);
  285. $eEnd->setTimezone($phpTZObject);
  286. $events[] = [
  287. "type" => "unavailability",
  288. "start" => $eStart->format('Y-m-d H:i:s'),
  289. "end" => $eEnd->format('Y-m-d H:i:s'),
  290. "editable" => false,
  291. "backgroundColor" => $_unavailableBG
  292. ];
  293. }
  294. return $events;
  295. }
  296. public function getMyClientIds($_search = false) {
  297. $clients = $this->getAccessibleClientsQuery($_search)->get();
  298. $clientIds = [];
  299. foreach($clients as $client){
  300. $clientIds[] = $client->id;
  301. }
  302. return $clientIds;
  303. }
  304. public function favoritesByCategory($_category) {
  305. return ProFavorite::where('pro_id', $this->id)
  306. ->where('is_removed', false)
  307. ->where('category', $_category)
  308. ->orderBy('category', 'asc')
  309. ->orderBy('position_index', 'asc')
  310. ->get();
  311. }
  312. public function favoritesByCategoryDecoded($_category) {
  313. $favorites = ProFavorite::where('pro_id', $this->id)
  314. ->where('is_removed', false)
  315. ->where('category', $_category)
  316. ->orderBy('category', 'asc')
  317. ->orderBy('position_index', 'asc')
  318. ->get();
  319. foreach ($favorites as $favorite) {
  320. if ($favorite->data) {
  321. $favorite->data = json_decode($favorite->data);
  322. }
  323. }
  324. return $favorites;
  325. }
  326. function get_patients_count_as_admin() {
  327. $query = Client::whereNull('shadow_pro_id');
  328. return $query->where('is_active', true)
  329. ->where(function ($q) {
  330. $q->whereNull('client_engagement_status_category')
  331. ->orWhere('client_engagement_status_category', '<>', 'DUMMY');
  332. })->count();
  333. }
  334. function get_patients_count_as_mcp() {
  335. $query = Client::whereNull('shadow_pro_id');
  336. return $query->where('mcp_pro_id', $this->id)
  337. ->where(function ($q) {
  338. $q->whereNull('client_engagement_status_category')
  339. ->orWhere('client_engagement_status_category', '<>', 'DUMMY');
  340. })->count();
  341. }
  342. function get_new_patients_awaiting_visit_count_as_mcp() {
  343. $query = Client::whereNull('shadow_pro_id');
  344. return $query->where('mcp_pro_id', $this->id)
  345. ->where('has_mcp_done_onboarding_visit', '!=', 'YES')
  346. ->count();
  347. }
  348. function get_new_patients_awaiting_visit_count_as_admin() {
  349. $query = Client::whereNull('shadow_pro_id');
  350. return $query->where('has_mcp_done_onboarding_visit', '!=', 'YES')
  351. ->count();
  352. }
  353. function get_notes_pending_signature_count_as_mcp() {
  354. return Note::where('hcp_pro_id', $this->id)
  355. ->where('is_cancelled', '<>', true)
  356. ->where('is_core_note', '<>', true)
  357. ->where('is_signed_by_hcp', '<>', true)
  358. ->count();
  359. }
  360. function get_notes_pending_signature_count_as_admin() {
  361. return Note::where('is_cancelled', '<>', true)
  362. ->where('is_core_note', '<>', true)
  363. ->where('is_signed_by_hcp', '<>', true)
  364. ->count();
  365. }
  366. function get_notes_pending_summary_suggestion_as_mcp_query(){
  367. $segmentsWithProposedSummarySuggestion = Segment::whereHas('proposedSegmentSummarySuggestion', function($sugQuery){
  368. return $sugQuery->where('status', '=', 'PENDING');
  369. })->get();
  370. $noteIDs = [];
  371. foreach($segmentsWithProposedSummarySuggestion as $seg){
  372. $noteIDs[] = $seg->note_id;
  373. }
  374. return Note::where('hcp_pro_id', $this->id)
  375. ->where('is_cancelled', '<>', true)
  376. ->where('is_core_note', '<>', true)
  377. ->where('is_signed_by_hcp', true)
  378. ->whereIn('id', $noteIDs);
  379. }
  380. function get_notes_rejected_summary_suggestion_as_mcp_query(){
  381. $segmentsWithProposedSummarySuggestion = Segment::whereHas('proposedSegmentSummarySuggestion', function($sugQuery){
  382. return $sugQuery->where('status', '=', 'REJECTED');
  383. })->get();
  384. $noteIDs = [];
  385. foreach($segmentsWithProposedSummarySuggestion as $seg){
  386. $noteIDs[] = $seg->note_id;
  387. }
  388. return Note::where('hcp_pro_id', $this->id)
  389. ->where('is_cancelled', '<>', true)
  390. ->where('is_core_note', '<>', true)
  391. ->where('is_signed_by_hcp', true)
  392. ->whereIn('id', $noteIDs);
  393. }
  394. function get_notes_pending_summary_suggestion_count_as_mcp(){
  395. return $this->get_notes_pending_summary_suggestion_as_mcp_query()->count();
  396. }
  397. function get_notes_pending_summary_suggestion_as_mcp(){
  398. return $this->get_notes_pending_summary_suggestion_as_mcp_query()->get();
  399. }
  400. function get_notes_rejected_summary_suggestion_count_as_mcp(){
  401. return $this->get_notes_rejected_summary_suggestion_as_mcp_query()->count();
  402. }
  403. function get_notes_rejected_summary_suggestion_as_mcp(){
  404. return $this->get_notes_rejected_summary_suggestion_as_mcp_query()->get();
  405. }
  406. function get_notes_pending_summary_suggestion_as_admin_query(){
  407. $segmentsWithProposedSummarySuggestion = Segment::whereHas('proposedSegmentSummarySuggestion', function($sugQuery){
  408. return $sugQuery->where('status', '=', 'PENDING');
  409. })->get();
  410. $noteIDs = [];
  411. foreach($segmentsWithProposedSummarySuggestion as $seg){
  412. $noteIDs[] = $seg->note_id;
  413. }
  414. return Note::where('is_cancelled', '<>', true)
  415. ->where('is_core_note', '<>', true)
  416. ->where('is_signed_by_hcp', true)
  417. ->whereIn('id', $noteIDs);
  418. }
  419. function get_notes_rejected_summary_suggestion_as_admin_query(){
  420. $segmentsWithProposedSummarySuggestion = Segment::whereHas('proposedSegmentSummarySuggestion', function($sugQuery){
  421. return $sugQuery->where('status', '=', 'REJECTED');
  422. })->get();
  423. $noteIDs = [];
  424. foreach($segmentsWithProposedSummarySuggestion as $seg){
  425. $noteIDs[] = $seg->note_id;
  426. }
  427. return Note::where('is_cancelled', '<>', true)
  428. ->where('is_core_note', '<>', true)
  429. ->where('is_signed_by_hcp', true)
  430. ->whereIn('id', $noteIDs);
  431. }
  432. function get_notes_pending_summary_suggestion_count_as_admin(){
  433. return $this->get_notes_pending_summary_suggestion_as_admin_query()->count();
  434. }
  435. function get_notes_pending_summary_suggestion_as_admin(){
  436. return $this->get_notes_pending_summary_suggestion_as_admin_query()->get();
  437. }
  438. function get_notes_rejected_summary_suggestion_count_as_admin(){
  439. return $this->get_notes_rejected_summary_suggestion_as_admin_query()->count();
  440. }
  441. function get_notes_rejected_summary_suggestion_as_admin(){
  442. return $this->get_notes_rejected_summary_suggestion_as_admin_query()->get();
  443. }
  444. function get_notes_pending_billing_count_as_mcp() {
  445. return Note::where('hcp_pro_id', $this->id)
  446. ->where('is_cancelled', '<>', true)
  447. ->where('is_signed_by_hcp', true)
  448. ->where('is_billing_marked_done', '<>', true)
  449. ->count();
  450. }
  451. function get_notes_pending_billing_count_as_admin() {
  452. return Note::where('is_cancelled', '<>', true)
  453. ->where('is_signed_by_hcp', true)
  454. ->where('is_billing_marked_done', '<>', true)
  455. ->count();
  456. }
  457. function get_measurements_awaiting_review_count_as_mcp() {
  458. $result = DB::select(DB::raw("
  459. SELECT SUM(rm_num_measurements_not_stamped_by_mcp) AS count
  460. FROM care_month
  461. WHERE mcp_pro_id = :pro_id
  462. AND rm_num_measurements_not_stamped_by_mcp IS NOT NULL
  463. AND rm_num_measurements_not_stamped_by_mcp > 0;
  464. "), ["pro_id" => $this->id]);
  465. if($result) return $result[0]->count;
  466. }
  467. function get_bills_pending_signature_count_as_mcp(){
  468. $pendingBillsToSign = Bill::where('bill_service_type', '<>', 'CARE_MONTH')->where(function ($query) {
  469. $query->where('hcp_pro_id', $this->id)->where('is_signed_by_hcp', false)->where('is_cancelled', false);
  470. })
  471. ->orWhere(function ($query) {
  472. $query->where('cm_pro_id', $this->id)->where('is_signed_by_cm', false)->where('is_cancelled', false);
  473. })->orWhere(function ($query) {
  474. $query->where('rme_pro_id', $this->id)->where('is_signed_by_rme', false)->where('is_cancelled', false);
  475. })->orWhere(function ($query) {
  476. $query->where('rmm_pro_id', $this->id)->where('is_signed_by_rmm', false)->where('is_cancelled', false);
  477. })->orWhere(function ($query) {
  478. $query->where('generic_pro_id', $this->id)->where('is_signed_by_generic_pro', false)->where('is_cancelled', false);
  479. })->count();
  480. return $pendingBillsToSign;
  481. }
  482. function get_incoming_reports_pending_signature_count_as_mcp() {
  483. return IncomingReport::where('hcp_pro_id', $this->id)
  484. ->where('has_hcp_pro_signed', '<>', true)
  485. ->where('is_entry_error', '<>', true)
  486. ->count();
  487. }
  488. function get_incoming_reports_pending_signature_count_as_admin() {
  489. return IncomingReport::where('has_hcp_pro_signed', '<>', true)
  490. ->where('is_entry_error', '<>', true)
  491. ->count();
  492. }
  493. function get_patients_without_appointment_query() {
  494. return Client::where('mcp_pro_id', $this->id)
  495. ->whereNull('today_mcp_appointment_date')
  496. ->where(function($q){
  497. $q->whereNull('next_mcp_appointment_id')
  498. ->orWhere('next_mcp_appointment_date', '<=', DB::raw('NOW()::DATE'));
  499. });
  500. }
  501. function get_patients_without_appointment_for_dna_query() {
  502. return Client::where('default_na_pro_id', $this->id)
  503. ->whereNull('today_mcp_appointment_date')
  504. ->where(function($q){
  505. $q->whereNull('next_mcp_appointment_id')
  506. ->orWhere('next_mcp_appointment_date', '<=', DB::raw('NOW()::DATE'));
  507. });
  508. }
  509. function get_patients_without_appointment_count_as_mcp() {
  510. return $this->get_patients_without_appointment_query()->count();
  511. }
  512. function get_patients_without_appointment_count_as_admin() {
  513. return Client::whereNull('shadow_pro_id')
  514. ->whereNull('today_mcp_appointment_date')
  515. ->where(function($q){
  516. $q->whereNull('next_mcp_appointment_id')
  517. ->orWhere('next_mcp_appointment_date', '<=', DB::raw('NOW()::DATE'));
  518. })->count();
  519. }
  520. function get_patients_overdue_for_visit_query() {
  521. return Client::where('mcp_pro_id', $this->id)
  522. ->where(function($q){
  523. $q->whereNull('most_recent_completed_mcp_note_id')
  524. ->orWhere('most_recent_completed_mcp_note_date', '<', DB::raw("NOW()::DATE - INTERVAL '45 DAY'"));
  525. });
  526. }
  527. function get_patients_overdue_for_visit_for_dna_query() {
  528. return Client::where('default_na_pro_id', $this->id)
  529. ->where(function($q){
  530. $q->whereNull('most_recent_completed_mcp_note_id')
  531. ->orWhere('most_recent_completed_mcp_note_date', '<', DB::raw("NOW()::DATE - INTERVAL '45 DAY'"));
  532. });
  533. }
  534. function get_patients_overdue_count_as_mcp() {
  535. return $this->get_patients_overdue_for_visit_query()->count();
  536. }
  537. function get_patients_without_remote_measurement_in_48_hours_count_as_mcp() {
  538. return DB::select("SELECT COUNT(*) as count FROM client WHERE ((most_recent_cellular_measurement_at+ interval '48 hour')::timestamp < NOW() OR most_recent_cellular_measurement_id IS NULL) AND client.mcp_pro_id = :mcp_pro_id AND is_active IS TRUE", ['mcp_pro_id'=>$this->id])[0]->count;
  539. }
  540. function get_cancelled_appointments_pending_acknowledgement_count_as_mcp_query() {
  541. // SELECT * FROM appointment WHERE hcp_pro_id = :me.id AND status = 'REJECTED' AND wasAcknowledgedByAppointmentPro IS NOT TRUE;
  542. return Appointment::where('pro_id', $this->id)
  543. ->where('latest_confirmation_decision_enum', 'REJECTED')
  544. ->where('is_decision_acknowledgement_from_appointment_pro_pending', true);
  545. }
  546. function get_cancelled_appointments_pending_acknowledgement_count_as_mcp() {
  547. // SELECT * FROM appointment WHERE hcp_pro_id = :me.id AND status = 'REJECTED' AND wasAcknowledgedByAppointmentPro IS NOT TRUE;
  548. return $this->get_cancelled_appointments_pending_acknowledgement_count_as_mcp_query()->count();
  549. }
  550. function get_cancelled_bills_awaiting_review_count_as_mcp() {
  551. // SELECT * FROM bill WHERE bill_service_type = 'NOTE' AND is_cancelled IS TRUE AND isCancellationAcknowledged IS FALSE;
  552. return Bill::where('hcp_pro_id', $this->id)
  553. ->where('bill_service_type', 'NOTE')
  554. ->where('is_cancelled', true)
  555. ->where('is_cancellation_acknowledged', '<>', true)
  556. ->count();
  557. }
  558. function get_cancelled_supply_orders_awaiting_review_count_as_mcp() {
  559. // SELECT * FROM supply_order WHERE signed_by_pro_id = :me.id AND is_cancelled IS TRUE AND isCancellationAcknowledged IS NOT TRUE;
  560. return SupplyOrder::where('signed_by_pro_id', $this->id)
  561. ->where('is_cancelled', true)
  562. ->where('is_cancellation_acknowledged', '<>', true)
  563. ->count();
  564. }
  565. function get_erx_and_orders_awaiting_signature_count_as_mcp() {
  566. // SELECT * FROM erx WHERE hcp_pro_id = :me.id AND pro_declared_status <> 'CANCELLED' AND hasHcpProSigned IS NOT TRUE;
  567. return Erx::where('hcp_pro_id', $this->id)
  568. ->where('pro_declared_status', '<>', 'CANCELLED')
  569. ->where('has_hcp_pro_signed', '<>', true)
  570. ->count();
  571. }
  572. function get_supply_orders_awaiting_signature_count_as_mcp() {
  573. // SELECT supply_order.id FROM supply_order WHERE signed_by_pro_id IS NOT TRUE AND is_cancelled IS NOT TRUE AND created_by_pro_id = :me.id;
  574. return SupplyOrder::where('created_by_pro_id', $this->id)
  575. ->whereNull('signed_by_pro_id')
  576. ->where('is_cancelled', '<>', true)
  577. ->count();
  578. }
  579. function get_supply_orders_awaiting_shipment_count_as_mcp() {
  580. return SupplyOrder::where('created_by_pro_id', $this->id)
  581. ->where('is_signed_by_pro', true)
  582. ->where('is_cleared_for_shipment', true)
  583. ->whereNull('shipment_id')
  584. ->count();
  585. }
  586. function get_unsigned_incoming_reports_count_as_mcp() {
  587. return IncomingReport::where('hcp_pro_id', $this->id)
  588. ->whereRaw('(has_hcp_pro_signed IS NULL OR has_hcp_pro_signed = FALSE)')
  589. ->count();
  590. }
  591. function get_unsigned_rpm_bills_count_as_mcp() {
  592. $query = "
  593. SELECT count(distinct(care_month.id))
  594. FROM care_month join client on care_month.client_id = client.id join note mrnote on client.most_recent_completed_mcp_note_id = mrnote.id
  595. left join bill on care_month.mcp_rm_generic_bill_id = bill.id
  596. left join note mrmnote on mrmnote.id = (
  597. select max(n.id) from note n
  598. where
  599. n.client_id = client.id AND
  600. n.is_cancelled = FALSE AND
  601. (n.is_signed_by_hcp IS NOT NULL AND n.is_signed_by_hcp = TRUE) AND
  602. n.effective_dateest::date >= care_month.start_date::date AND
  603. n.effective_dateest::date < (care_month.start_date::date + INTERVAL '1 month')
  604. )
  605. WHERE
  606. care_month.mcp_pro_id = {$this->id}
  607. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  608. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  609. AND care_month.mcp_rm_generic_bill_id IS NOT NULL
  610. AND bill.is_signed_by_generic_pro = TRUE
  611. ";
  612. // dd($query);
  613. $count = DB::select($query);
  614. return $count[0]->count;
  615. }
  616. function get_unsigned_rpm_bills_count_as_rmm() {
  617. $query = "
  618. SELECT count(distinct(care_month.id))
  619. FROM care_month join client on care_month.client_id = client.id join note mrnote on client.most_recent_completed_mcp_note_id = mrnote.id
  620. left join bill on care_month.rmm_rm_generic_bill_id = bill.id
  621. left join note mrmnote on mrmnote.id = (
  622. select max(n.id) from note n
  623. where
  624. n.client_id = client.id AND
  625. n.is_cancelled = FALSE AND
  626. (n.is_signed_by_hcp IS NOT NULL AND n.is_signed_by_hcp = TRUE) AND
  627. n.effective_dateest::date >= care_month.start_date::date AND
  628. n.effective_dateest::date < (care_month.start_date::date + INTERVAL '1 month')
  629. )
  630. WHERE
  631. care_month.rmm_pro_id = {$this->id}
  632. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  633. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  634. AND care_month.rmm_rm_generic_bill_id IS NOT NULL
  635. AND bill.is_signed_by_generic_pro = TRUE
  636. ";
  637. // dd($query);
  638. $count = DB::select($query);
  639. return $count[0]->count;
  640. }
  641. function get_patients_awaiting_rpm_interaction_count_as_mcp() {
  642. $cmStartDate = date('Y-m-01');
  643. $query = "
  644. SELECT
  645. count(client.id)
  646. FROM
  647. client join care_month on client.id = care_month.client_id
  648. WHERE
  649. care_month.start_date = '{$cmStartDate}'
  650. AND client.is_enrolled_in_rm = 'YES'
  651. AND care_month.has_mcp_interacted_with_client_about_rm IS NOT TRUE
  652. AND care_month.mcp_pro_id = {$this->id}
  653. AND (client.client_engagement_status_category IS NULL OR client.client_engagement_status_category != 'DUMMY')
  654. AND client.name_first NOT ILIKE '%test%'
  655. AND client.name_last NOT ILIKE '%test%'
  656. ";
  657. $count = DB::select($query);
  658. return $count[0]->count;
  659. }
  660. function get_birthdays_today_as_mcp(){
  661. return;
  662. $queryClients = $this->performer()->pro->getAccessibleClientsQuery();
  663. $keyNumbers['patientsHavingBirthdayToday'] = $queryClients
  664. ->whereRaw('EXTRACT(DAY from dob) = ?', [date('d')])
  665. ->whereRaw('EXTRACT(MONTH from dob) = ?', [date('m')])
  666. ->count();
  667. $reimbursement = [];
  668. $reimbursement["currentBalance"] = $performer->pro->balance;
  669. $reimbursement["nextPaymentDate"] = '--';
  670. $lastPayment = ProTransaction::where('pro_id', $performerProID)->where('plus_or_minus', 'PLUS')->orderBy('created_at', 'DESC')->first();
  671. if ($lastPayment) {
  672. $reimbursement["lastPayment"] = $lastPayment->amount;
  673. $reimbursement["lastPaymentDate"] = $lastPayment->created_at;
  674. } else {
  675. $reimbursement["lastPayment"] = '--';
  676. $reimbursement["lastPaymentDate"] = '--';
  677. }
  678. }
  679. public function getAppointmentsPendingStatusChangeAck() {
  680. return Appointment::where('pro_id', $this->id)
  681. ->where('is_status_acknowledgement_from_appointment_pro_pending', true)
  682. //->where('raw_date', '>=', DB::raw('NOW()'))
  683. ->orderBy('raw_date', 'asc')
  684. ->get();
  685. }
  686. public function getAppointmentsPendingDecisionAck() {
  687. return Appointment::where('pro_id', $this->id)
  688. ->where('is_decision_acknowledgement_from_appointment_pro_pending', true)
  689. //->where('raw_date', '>=', DB::raw('NOW()'))
  690. ->orderBy('raw_date', 'asc')
  691. ->get();
  692. }
  693. public function getAppointmentsPendingTimeChangeAck() {
  694. return Appointment::where('pro_id', $this->id)
  695. ->where('is_time_change_acknowledgement_from_appointment_pro_pending', true)
  696. //->where('raw_date', '>=', DB::raw('NOW()'))
  697. ->orderBy('raw_date', 'asc')
  698. ->get();
  699. }
  700. public function getAccessibleClientsQuery($_search = false) {
  701. $proID = $this->id;
  702. $query = Client::whereNull('shadow_pro_id');
  703. if ($this->pro_type === 'ADMIN' && ($_search ? $this->can_see_any_client_via_search : $this->can_see_all_clients_in_list)) {
  704. $query = $query->where('id', '>', 0);
  705. } else {
  706. $query = $query->where(function ($q) use ($proID) {
  707. $q->where('mcp_pro_id', $proID)
  708. ->orWhere('cm_pro_id', $proID)
  709. ->orWhere('rmm_pro_id', $proID)
  710. ->orWhere('rme_pro_id', $proID)
  711. ->orWhere('physician_pro_id', $proID)
  712. ->orWhere('default_na_pro_id', $proID)
  713. ->orWhereRaw('id IN (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = ?)', [$proID])
  714. ->orWhereRaw('id IN (SELECT client_id FROM appointment WHERE status NOT IN (\'CANCELLED\') AND pro_id = ?)', [$proID])
  715. ->orWhereRaw('id IN (SELECT mcp_pro_id FROM client_program WHERE client_id = client.id AND is_active = TRUE)')
  716. ->orWhereRaw('id IN (SELECT manager_pro_id FROM client_program WHERE client_id = client.id AND is_active = TRUE)')
  717. ->orWhereRaw('id IN (SELECT client_id FROM note WHERE ally_pro_id = ? AND is_cancelled = FALSE)', [$proID]);;
  718. });
  719. }
  720. return $query;
  721. }
  722. public function canAccess($_patientUid) {
  723. $proID = $this->id;
  724. if ($this->pro_type === 'ADMIN') {
  725. return true;
  726. }
  727. $canAccess = Client::select('uid')
  728. ->where('uid', $_patientUid)
  729. ->where(function ($q) use ($proID) {
  730. $q->whereNull('mcp_pro_id')
  731. ->orWhere('mcp_pro_id', $proID)
  732. ->orWhere('cm_pro_id', $proID)
  733. ->orWhere('rmm_pro_id', $proID)
  734. ->orWhere('rme_pro_id', $proID)
  735. ->orWhere('physician_pro_id', $proID)
  736. ->orWhere('default_na_pro_id', $proID)
  737. ->orWhereRaw('id IN (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = ?)', [$proID])
  738. ->orWhereRaw('id IN (SELECT client_id FROM appointment WHERE status NOT IN (\'CANCELLED\') AND pro_id = ?)', [$proID])
  739. ->orWhereRaw('id IN (SELECT mcp_pro_id FROM client_program WHERE client_id = client.id AND is_active = TRUE)')
  740. ->orWhereRaw('id IN (SELECT manager_pro_id FROM client_program WHERE client_id = client.id AND is_active = TRUE)')
  741. ->orWhereRaw('id IN (SELECT client_id FROM note WHERE ally_pro_id = ? AND is_cancelled = FALSE)', [$proID]);
  742. })->count();
  743. return !!$canAccess;
  744. }
  745. public function canAddCPMEntryForMeasurement(Measurement $measurement, Pro $pro)
  746. {
  747. // check if client has any programs where this measurement type is allowed
  748. $allowed = false;
  749. $client = $measurement->client;
  750. $clientPrograms = $client->clientPrograms;
  751. if($pro->pro_type !== 'ADMIN') {
  752. $clientPrograms = $clientPrograms->filter(function($_clientProgram) use ($pro) {
  753. return $_clientProgram->manager_pro_id === $pro->id;
  754. });
  755. }
  756. if(count($clientPrograms)) {
  757. foreach ($clientPrograms as $clientProgram) {
  758. if(strpos(strtolower($clientProgram->measurement_labels), '|' . strtolower($measurement->label) . '|') !== FALSE) {
  759. $allowed = true;
  760. break;
  761. }
  762. }
  763. }
  764. return $allowed ? $clientPrograms : FALSE;
  765. }
  766. public function getUnstampedMeasurementsFromCurrentMonth($_countOnly, $skip, $limit)
  767. {
  768. date_default_timezone_set('US/Eastern');
  769. $start = strtotime(date('Y-m-01'));
  770. $end = date_add(date_create(date('Y-m-01')), date_interval_create_from_date_string("1 month"))->getTimestamp();
  771. $start *= 1000;
  772. $end *= 1000;
  773. $measurementsQuery = Measurement::where('measurement.is_active', true)
  774. ->join('client', 'client.id', '=', 'measurement.client_id')
  775. ->whereNotNull('measurement.client_bdt_measurement_id')
  776. ->whereNotNull('measurement.ts')
  777. ->where('measurement.is_cellular_zero', false)
  778. ->where('measurement.ts', '>=', $start)
  779. ->where('measurement.ts', '<', $end)
  780. ->whereIn('measurement.client_id', $this->getMyClientIds())
  781. ->where(function ($q) {
  782. $q
  783. ->where(function ($q2) {
  784. $q2
  785. ->where('client.mcp_pro_id', $this->id)
  786. ->where('measurement.has_been_stamped_by_mcp', false);
  787. })
  788. ->orWhere(function ($q2) {
  789. $q2
  790. ->where('client.default_na_pro_id', $this->id)
  791. ->where('measurement.has_been_stamped_by_non_hcp', false);
  792. })
  793. ->orWhere(function ($q2) {
  794. $q2
  795. ->where('client.rmm_pro_id', $this->id)
  796. ->where('measurement.has_been_stamped_by_rmm', false);
  797. })
  798. ->orWhere(function ($q2) {
  799. $q2
  800. ->where('client.rme_pro_id', $this->id)
  801. ->where('measurement.has_been_stamped_by_rme', false);
  802. });
  803. });
  804. if($_countOnly) {
  805. return $measurementsQuery->count();
  806. }
  807. $x = [];
  808. $measurements = $measurementsQuery
  809. ->orderBy('ts', 'desc')
  810. ->skip($skip)
  811. ->take($limit)
  812. ->get();
  813. // eager load stuff needed in JS
  814. foreach ($measurements as $measurement) {
  815. // if ($measurement->client_bdt_measurement_id) {
  816. // $measurement->bdtMeasurement = $measurement->clientBDTMeasurement->measurement;
  817. // }
  818. unset($measurement->clientBDTMeasurement); // we do not need this travelling to the frontend
  819. $client = [
  820. "uid" => $measurement->client->uid,
  821. "name" => $measurement->client->displayName(),
  822. ];
  823. $measurement->patient = $client;
  824. $measurement->careMonth = $measurement->client->currentCareMonth();
  825. $measurement->timestamp = friendlier_date_time($measurement->created_at);
  826. unset($measurement->client); // we do not need this travelling to the frontend
  827. if(@$measurement->detail_json) unset($measurement->detail_json);
  828. if(@$measurement->canvas_data) unset($measurement->canvas_data);
  829. if(@$measurement->latest_measurements) unset($measurement->latest_measurements);
  830. if(@$measurement->info_lines) unset($measurement->info_lines);
  831. if(@$measurement->canvas_data_backup) unset($measurement->canvas_data_backup);
  832. if(@$measurement->migrated_canvas_data_backup) unset($measurement->migrated_canvas_data_backup);
  833. // if($measurement->label == 'SBP' || $measurement->label = 'DBP'){
  834. // continue;
  835. // }
  836. $x[] = $measurement;
  837. }
  838. // dd($measurements);
  839. return $measurements;
  840. }
  841. public function getMeasurements($_onlyUnstamped = true)
  842. {
  843. $measurementsQuery = Measurement::where('is_removed', false);
  844. if ($this->pro_type != 'ADMIN') {
  845. $measurementsQuery
  846. ->whereIn('client_id', $this->getMyClientIds());
  847. }
  848. if ($_onlyUnstamped) {
  849. $measurementsQuery
  850. ->whereNotNull('client_bdt_measurement_id')
  851. ->whereNotNull('ts')
  852. ->where('is_cellular_zero', false)
  853. ->where(function ($q) {
  854. $q->whereNull('status')
  855. ->orWhere(function ($q2) {
  856. $q2->where('status', '<>', 'ACK')
  857. ->where('status', '<>', 'INVALID_ACK');
  858. });
  859. });
  860. }
  861. $x = [];
  862. $measurements = $measurementsQuery->orderBy('ts', 'desc')->paginate(50);
  863. // eager load stuff needed in JS
  864. foreach ($measurements as $measurement) {
  865. // if ($measurement->client_bdt_measurement_id) {
  866. // $measurement->bdtMeasurement = $measurement->clientBDTMeasurement->measurement;
  867. // }
  868. unset($measurement->clientBDTMeasurement); // we do not need this travelling to the frontend
  869. $client = [
  870. "uid" => $measurement->client->uid,
  871. "name" => $measurement->client->displayName(),
  872. ];
  873. $measurement->patient = $client;
  874. $measurement->careMonth = $measurement->client->currentCareMonth();
  875. $measurement->timestamp = friendly_date_time($measurement->created_at);
  876. unset($measurement->client); // we do not need this travelling to the frontend
  877. // if($measurement->label == 'SBP' || $measurement->label = 'DBP'){
  878. // continue;
  879. // }
  880. $x[] = $measurement;
  881. }
  882. return $measurements;
  883. }
  884. public function companyPros()
  885. {
  886. return $this->hasMany(CompanyPro::class, 'pro_id', 'id')
  887. ->where('is_active', true);
  888. }
  889. public function companyProPayers()
  890. {
  891. return $this->hasMany(CompanyProPayer::class, 'pro_id', 'id');
  892. }
  893. public function isAssociatedWithMCPayer() {
  894. $companyProPayers = $this->companyProPayers;
  895. $foundMC = false;
  896. if($companyProPayers) {
  897. foreach ($companyProPayers as $companyProPayer) {
  898. if($companyProPayer->payer && $companyProPayer->payer->is_medicare) {
  899. $foundMC = true;
  900. break;
  901. }
  902. }
  903. }
  904. return $foundMC;
  905. }
  906. public function isAssociatedWithNonMCPayer($_payerID) {
  907. $companyProPayers = $this->companyProPayers;
  908. $foundNonMC = false;
  909. if($companyProPayers) {
  910. foreach ($companyProPayers as $companyProPayer) {
  911. if($companyProPayer->payer && !$companyProPayer->payer->is_medicare && $companyProPayer->payer->id === $_payerID) {
  912. $foundNonMC = true;
  913. break;
  914. }
  915. }
  916. }
  917. return $foundNonMC;
  918. }
  919. public function companyLocations() {
  920. $companyProPayers = $this->companyProPayers;
  921. $companyIDs = [];
  922. foreach ($companyProPayers as $companyProPayer) {
  923. $companyIDs[] = $companyProPayer->company_id;
  924. }
  925. $locations = [];
  926. if(count($companyIDs)) {
  927. $locations = CompanyLocation::whereIn('id', $companyIDs)->get();
  928. }
  929. return $locations;
  930. }
  931. public function shadowClient() {
  932. return $this->hasOne(Client::class, 'id', 'shadow_client_id');
  933. }
  934. public function defaultCompanyPro() {
  935. return $this->hasOne(CompanyPro::class, 'id', 'default_company_pro_id');
  936. }
  937. public function currentNotePickupForProcessing() {
  938. return $this->hasOne(NotePickupForProcessing::class, 'id', 'current_note_pickup_for_processing_id');
  939. }
  940. public function get_patients_not_seen_in_45_days_count_as_mcp(){
  941. return 0;
  942. }
  943. public function get_open_tickets_count_as_mcp(){
  944. $self = $this;
  945. return Ticket::where(function ($q) use ($self) {
  946. $q->where('assigned_pro_id', $self->id)
  947. ->orWhere('manager_pro_id', $self->id)
  948. ->orWhere('ordering_pro_id', $self->id)
  949. ->orWhere('initiating_pro_id', $self->id);
  950. })
  951. ->where('category', 'other')
  952. ->where('is_open', true)
  953. ->count();
  954. }
  955. //DNA_DASHBOARD
  956. //queries
  957. private function patientsQueryAsDna(){
  958. // WHERE na_pro_id = :me.id
  959. return Client::where('default_na_pro_id', $this->id);
  960. }
  961. private function patientsAwaitingMcpVisitQueryAsDna(){
  962. // WHERE has_mcp_done_onboarding_visit <> 'YES'
  963. return Client::where('default_na_pro_id', $this->id)->where('has_mcp_done_onboarding_visit', '<>', 'YES');
  964. }
  965. private function patientsWithoutAppointmentQueryAsDna(){
  966. // WHERE today_mcp_appointment_date IS NULL AND next_mcp_appointment_date IS NULL
  967. return Client::where('default_na_pro_id', $this->id)
  968. ->whereNull('today_mcp_appointment_date')
  969. ->whereNull('next_mcp_appointment_date');
  970. }
  971. private function encountersPendingMyReviewQueryAsDna(){
  972. // WHERE ally_pro_id = me.id AND is_cancelled IS NOT TRUE AND is_signed_by_hcp IS TRUE AND is_signed_by_ally IS NOT TRUE;
  973. return Note::where('ally_pro_id', $this->id)
  974. ->where('is_cancelled', '<>', true)
  975. ->where('is_signed_by_hcp', true)
  976. ->where('is_signed_by_ally','<>', true);
  977. }
  978. private function encountersInProgressQueryAsDna(){
  979. // SELECT * FROM note WHERE ally_pro_id = me.id AND is_cancelled IS NOT TRUE AND is_signed_by_hcp IS NOT TRUE ORDER BY effective_dateest DESC, created_at DESC;
  980. return Note::where('ally_pro_id', $this->id)
  981. ->where('is_cancelled', '<>', true)
  982. ->where('is_signed_by_hcp', '<>', true);
  983. }
  984. private function appointmentsPendingConfirmationQueryAsDna(){
  985. // WHERE client_id IN (SELECT id FROM client WHERE default_na_pro_id = :me.id) AND status = 'PENDING'
  986. $myId = $this->id;
  987. return Appointment::whereHas('client', function($clientQuery) use ($myId) {
  988. return $clientQuery->where('default_na_pro_id', $myId);
  989. })->where('status', 'PENDING');
  990. }
  991. private function cancelledAppointmentsPendingAckQueryAsDna(){
  992. // WHERE client_id IN (SELECT id FROM client WHERE default_na_pro_id = :me.id) AND status = 'CANCELLED' AND is_status_acknowledgement_from_default_na_pending IS TRUE;
  993. $myId = $this->id;
  994. return Appointment::whereHas('client', function($clientQuery) use ($myId) {
  995. return $clientQuery->where('default_na_pro_id', $myId);
  996. })->where('status', 'CANCELLED')
  997. ->where('is_status_acknowledgement_from_default_na_pending', true);
  998. }
  999. private function reportsPendingAckQueryAsDna(){
  1000. // WHERE client_id IN (SELECT id FROM client WHERE default_na_pro_id = :me.id) AND has_na_pro_signed IS FALSE AND is_entry_error
  1001. $myId = $this->id;
  1002. return IncomingReport::whereHas('client',function($clientQuery) use ($myId) {
  1003. return $clientQuery->where('default_na_pro_id', $myId);
  1004. })->where('has_na_pro_signed', '<>', true)
  1005. ->where('is_entry_error','<>', true);
  1006. }
  1007. private function supplyOrdersPendingMyAckQueryAsDna(){
  1008. // WHERE client_id IN (SELECT id FROM client WHERE default_na_pro_id = :me.id) AND has_na_pro_signed IS FALSE AND is_signed_by_pro IS TRUE AND is_cancelled IS NOT TRUE;
  1009. $myId = $this->id;
  1010. return SupplyOrder::whereHas('client',function($clientQuery) use ($myId) {
  1011. return $clientQuery->where('default_na_pro_id', $myId);
  1012. })->where('has_na_pro_signed', '<>', true)
  1013. ->where('is_signed_by_pro', true)
  1014. ->where('is_cancelled', '<>', true);
  1015. }
  1016. private function supplyOrdersPendingHcpApprovalQueryAsDna(){
  1017. // WHERE client_id IN (SELECT id FROM client WHERE default_na_pro_id = :me.id) AND has_na_pro_signed IS TRUE AND is_signed_by_pro IS NOT TRUE AND is_cancelled IS NOT TRUE;
  1018. $myId = $this->id;
  1019. return SupplyOrder::whereHas('client',function($clientQuery) use ($myId) {
  1020. return $clientQuery->where('default_na_pro_id', $myId);
  1021. })->where('has_na_pro_signed', true)
  1022. ->where('is_signed_by_pro','<>', true)
  1023. ->where('is_cancelled', '<>', true);
  1024. }
  1025. //counts
  1026. public function patientsCountAsDna(){
  1027. return $this->patientsQueryAsDna()->count();
  1028. }
  1029. public function patientsAwaitingMcpVisitCountAsDna(){
  1030. return $this->patientsAwaitingMcpVisitQueryAsDna()->count();
  1031. }
  1032. public function patientsWithoutAppointmentCountAsDna(){
  1033. return $this->patientsWithoutAppointmentQueryAsDna()->count();
  1034. }
  1035. public function encountersPendingMyReviewCountAsDna(){
  1036. return $this->encountersPendingMyReviewQueryAsDna()->count();
  1037. }
  1038. public function encountersInProgressCountAsDna(){
  1039. return $this->encountersInProgressQueryAsDna()->count();
  1040. }
  1041. public function appointmentsPendingConfirmationCountAsDna(){
  1042. return $this->appointmentsPendingConfirmationQueryAsDna()->count();
  1043. }
  1044. public function cancelledAppointmentsPendingAckCountAsDna(){
  1045. return $this->cancelledAppointmentsPendingAckQueryAsDna()->count();
  1046. }
  1047. public function reportsPendingAckCountAsDna(){
  1048. return $this->reportsPendingAckQueryAsDna()->count();
  1049. }
  1050. public function supplyOrdersPendingMyAckCountAsDna(){
  1051. return $this->supplyOrdersPendingMyAckQueryAsDna()->count();
  1052. }
  1053. public function supplyOrdersPendingHcpApprovalCountAsDna(){
  1054. return $this->supplyOrdersPendingHcpApprovalQueryAsDna()->count();
  1055. }
  1056. //records
  1057. private $DNA_RESULTS_PAGE_SIZE = 50;
  1058. public function patientsRecordsAsDna(){
  1059. return $this->patientsQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  1060. }
  1061. public function patientsAwaitingMcpVisitRecordsAsDna(){
  1062. return $this->patientsAwaitingMcpVisitQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  1063. }
  1064. public function patientsWithoutAppointmentRecordsAsDna(){
  1065. return $this->patientsWithoutAppointmentQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  1066. }
  1067. public function encountersPendingMyReviewRecordsAsDna(){
  1068. return $this->encountersPendingMyReviewQueryAsDna()
  1069. ->orderBy('effective_dateest', 'desc')
  1070. ->orderBy('created_at', 'desc')
  1071. ->paginate($this->DNA_RESULTS_PAGE_SIZE);
  1072. }
  1073. public function encountersInProgressRecordsAsDna(){
  1074. return $this->encountersInProgressQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  1075. }
  1076. public function appointmentsPendingConfirmationRecordsAsDna(){
  1077. return $this->appointmentsPendingConfirmationQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  1078. }
  1079. public function cancelledAppointmentsPendingAckRecordsAsDna(){
  1080. return $this->cancelledAppointmentsPendingAckQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  1081. }
  1082. public function reportsPendingAckRecordsAsDna(){
  1083. return $this->reportsPendingAckQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  1084. }
  1085. public function supplyOrdersPendingMyAckRecordsAsDna(){
  1086. return $this->supplyOrdersPendingMyAckQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  1087. }
  1088. public function supplyOrdersPendingHcpApprovalRecordsAsDna(){
  1089. return $this->supplyOrdersPendingHcpApprovalQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  1090. }
  1091. public function measurementsPendingReviewAsDna(){
  1092. //Measurements Pending Review
  1093. // SELECT * FROM measurement WHERE client_id IN (SELECT id FROM client WHERE rmm_pro_id = :me.id)
  1094. // AND has_been_stamped_by_rmm IS FALSE AND is_cellular IS TRUE AND is_cellular_zero IS NOT TRUE AND is_active IS TRUE ORDER BY ts DESC;
  1095. $myId = $this->id;
  1096. return Measurement::whereHas('client',function($clientQuery) use ($myId) {
  1097. return $clientQuery->where('rmm_pro_id', $myId);
  1098. })
  1099. ->where('has_been_stamped_by_rmm', '<>', true)
  1100. ->where('is_cellular', true)
  1101. ->where('is_cellular_zero', '<>', true)
  1102. ->where('is_active', true)
  1103. ->orderBy('ts', 'DESC')
  1104. ->paginate(15);
  1105. }
  1106. public function getProcessingAmountAsDna(){
  1107. $expectedForCm = DB::select(DB::raw("SELECT coalesce(SUM(cm_expected_payment_amount),0) as expected_pay FROM bill WHERE cm_pro_id = :performerProID AND has_cm_been_paid = false AND is_signed_by_cm IS TRUE AND is_cancelled = false"), ['performerProID' => $this->id])[0]->expected_pay;
  1108. $expectedForRme = DB::select(DB::raw("SELECT coalesce(SUM(rme_expected_payment_amount),0) as expected_pay FROM bill WHERE rme_pro_id = :performerProID AND has_rme_been_paid = false AND is_signed_by_rme IS TRUE AND is_cancelled = false"), ['performerProID' => $this->id])[0]->expected_pay;
  1109. $expectedForRmm = DB::select(DB::raw("SELECT coalesce(SUM(rmm_expected_payment_amount),0) as expected_pay FROM bill WHERE rmm_pro_id = :performerProID AND has_rmm_been_paid = false AND is_signed_by_rmm IS TRUE AND is_cancelled = false"), ['performerProID' => $this->id])[0]->expected_pay;
  1110. $expectedForNa = DB::select(DB::raw("SELECT coalesce(SUM(generic_pro_expected_payment_amount),0) as expected_pay FROM bill WHERE generic_pro_id = :performerProID AND has_generic_pro_been_paid = false AND is_signed_by_generic_pro IS TRUE AND is_cancelled = false"), ['performerProID' => $this->id])[0]->expected_pay;
  1111. $totalExpectedAmount = $expectedForCm + $expectedForRme + $expectedForRmm + $expectedForNa;
  1112. return $totalExpectedAmount;
  1113. }
  1114. public function getNextPaymentDateAsDna(){
  1115. $nextPaymentDate = '--';
  1116. //if today is < 15th, next payment is 15th, else nextPayment is
  1117. $today = strtotime(date('Y-m-d'));
  1118. $todayDate = date('j', $today);
  1119. $todayMonth = date('m', $today);
  1120. $todayYear = date('Y', $today);
  1121. if ($todayDate < 15) {
  1122. $nextPaymentDate = new DateTime();
  1123. $nextPaymentDate->setDate($todayYear, $todayMonth, 15);
  1124. $nextPaymentDate = $nextPaymentDate->format('m/d/Y');
  1125. } else {
  1126. $nextPaymentDate = new \DateTime();
  1127. $lastDayOfMonth = date('t', $today);
  1128. $nextPaymentDate->setDate($todayYear, $todayMonth, $lastDayOfMonth);
  1129. $nextPaymentDate = $nextPaymentDate->format('m/d/Y');
  1130. }
  1131. return $nextPaymentDate;
  1132. }
  1133. public function clientSmsesAsDna(){
  1134. $myId = $this->id;
  1135. return ClientSMS::whereHas('client', function($clientQuery) use ($myId){
  1136. return $clientQuery->where('default_na_pro_id', $myId);
  1137. })
  1138. ->orderBy('created_at', 'DESC')
  1139. ->paginate(15);
  1140. }
  1141. public function clientMemosAsDna(){
  1142. $naClientMemos = DB::select(
  1143. DB::raw("
  1144. SELECT c.uid as client_uid, c.name_first, c.name_last,
  1145. cm.uid, cm.content, cm.created_at
  1146. FROM client c join client_memo cm on c.id = cm.client_id
  1147. WHERE
  1148. c.default_na_pro_id = {$this->id}
  1149. ORDER BY cm.created_at DESC
  1150. ")
  1151. );
  1152. return $naClientMemos;
  1153. }
  1154. public function getAppointmentsPendingStatusChangeAckAsDna() {
  1155. $myId = $this->id;
  1156. return Appointment::whereHas('client', function($clientQuery) use ($myId){
  1157. return $clientQuery->where('default_na_pro_id', $myId);
  1158. })
  1159. ->where('is_status_acknowledgement_from_appointment_pro_pending', true)
  1160. ->where('raw_date', '>=', DB::raw('NOW()'))
  1161. ->orderBy('raw_date', 'asc')
  1162. ->get();
  1163. }
  1164. public function getAppointmentsPendingDecisionAckAsDna() {
  1165. $myId = $this->id;
  1166. return Appointment::whereHas('client', function($clientQuery) use ($myId){
  1167. return $clientQuery->where('default_na_pro_id', $myId);
  1168. })
  1169. ->where('is_decision_acknowledgement_from_appointment_pro_pending', true)
  1170. ->where('raw_date', '>=', DB::raw('NOW()'))
  1171. ->orderBy('raw_date', 'asc')
  1172. ->get();
  1173. }
  1174. public function getAppointmentsPendingTimeChangeAckAsDna() {
  1175. $myId = $this->id;
  1176. return Appointment::whereHas('client', function($clientQuery) use ($myId){
  1177. return $clientQuery->where('default_na_pro_id', $myId);
  1178. })
  1179. ->where('is_time_change_acknowledgement_from_appointment_pro_pending', true)
  1180. ->where('raw_date', '>=', DB::raw('NOW()'))
  1181. ->orderBy('raw_date', 'asc')
  1182. ->get();
  1183. }
  1184. function myGenericBills() {
  1185. return Bill::where('bill_service_type', 'GENERIC')
  1186. ->where('generic_pro_id', $this->id)
  1187. ->orderBy('created_at', 'DESC')->get();
  1188. }
  1189. public function myNotesPendingSupervisorPhysicianStamping(){
  1190. $pro = $this;
  1191. return Note::where('is_stamped_by_supervising_physician', false)->where('is_flagged_for_supervising_physician_review', true)->whereHas('hcpCompanyPro', function($qry) use($pro){
  1192. return $qry->whereHas('supervisingPhysicianCompanyPro', function($qr) use($pro){
  1193. return $qr->where('pro_id', $pro->id);
  1194. });
  1195. })->count();
  1196. }
  1197. public function activeClientReviewRequests()
  1198. {
  1199. return $this->hasMany(ClientReviewRequest::class, 'pro_id')->where('is_active', true);
  1200. }
  1201. }