Pro.php 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  1. <?php
  2. namespace App\Models;
  3. # use Illuminate\Database\Eloquent\Model;
  4. use App\Helpers\TimeLine;
  5. use Exception;
  6. use Illuminate\Support\Facades\DB;
  7. class Pro extends Model
  8. {
  9. protected $table = 'pro';
  10. public function displayName() {
  11. $name = [];
  12. if(!empty($this->name_display)) return $this->name_display;
  13. if(!empty($this->name_last)) $name[] = $this->name_last;
  14. if(!empty($this->name_first)) $name[] = $this->name_first;
  15. if(!count($name)) {
  16. $name = $this->name_display;
  17. }
  18. else {
  19. $name = implode(", ", $name);
  20. }
  21. return $name;
  22. }
  23. public function initials() {
  24. $characters = [];
  25. if(!empty($this->name_first)) $characters[] = $this->name_first[0];
  26. if(!empty($this->name_last)) $characters[] = $this->name_last[0];
  27. return strtolower(implode("", $characters));
  28. }
  29. public function debitBills()
  30. {
  31. return $this->hasMany(Bill::class, 'debit_pro_id');
  32. }
  33. public function cmBills()
  34. {
  35. return $this->hasMany(Bill::class, 'cm_pro_id');
  36. }
  37. public function hcpBills()
  38. {
  39. return $this->hasMany(Bill::class, 'hcp_pro_id');
  40. }
  41. public function teamsWhereAssistant()
  42. {
  43. return $this->hasMany(ProTeam::class, 'assistant_pro_id', 'id');
  44. }
  45. public function isDefaultNA()
  46. {
  47. // TODO are we using this?
  48. return true; // $this->is_considered_for_dna;
  49. }
  50. public function lastPayment() {
  51. return ProTransaction
  52. ::where('pro_id', $this->id)
  53. ->where('plus_or_minus', 'PLUS')
  54. ->orderBy('created_at', 'desc')
  55. ->first();
  56. }
  57. public function hasRates() {
  58. $numRates = ProRate::where('is_active', true)->where('pro_id', $this->id)->count();
  59. return $numRates > 0;
  60. }
  61. public function cmRates() {
  62. return ProRate::distinct('code')
  63. ->where('is_active', true)
  64. ->where('pro_id', $this->id)
  65. ->where('code', 'LIKE', 'CM%')
  66. ->get();
  67. }
  68. public function rmRates() {
  69. return ProRate::distinct('code')
  70. ->where('is_active', true)
  71. ->where('pro_id', $this->id)
  72. ->where('code', 'LIKE', 'RM%')
  73. ->get();
  74. }
  75. public function noteRates() {
  76. return ProRate::distinct('code')
  77. ->where('is_active', true)
  78. ->where('pro_id', $this->id)
  79. ->where('code', 'NOT LIKE', 'CM%')
  80. ->where('code', 'NOT LIKE', 'RM%')
  81. ->where('responsibility', '<>', 'GENERIC')
  82. ->get();
  83. }
  84. public function genericRates() {
  85. return ProRate::distinct('code')
  86. ->where('is_active', true)
  87. ->where('pro_id', $this->id)
  88. ->where('responsibility', 'GENERIC')
  89. ->get();
  90. }
  91. public function recentDebits() {
  92. return ProTransaction
  93. ::where('pro_id', $this->id)
  94. ->where('plus_or_minus', 'PLUS')
  95. ->orderBy('created_at', 'desc')
  96. ->skip(0)->take(4)->get();
  97. }
  98. public function shortcuts() {
  99. return $this->hasMany(ProTextShortcut::class, 'pro_id')->where('is_removed', false);
  100. }
  101. public function allShortcuts() {
  102. $myId = $this->id;
  103. $shortcuts = ProTextShortcut::where('is_removed', false)
  104. ->where(function ($query2) use ($myId) {
  105. $query2
  106. ->where('pro_id', $myId)
  107. ->orWhereNull('pro_id');
  108. })
  109. ->get();
  110. return $shortcuts;
  111. }
  112. public function noteTemplates() {
  113. return $this->hasMany(NoteTemplatePro::class, 'pro_id')
  114. ->where('is_removed', false)
  115. ->orderBy('position_index', 'asc');
  116. }
  117. public function visitTemplates() {
  118. //TODO: use visit access
  119. return VisitTemplate::all();
  120. }
  121. public function currentWork() {
  122. return ProClientWork::where('pro_id', $this->id)->where('is_active', true)->first();
  123. }
  124. public function isWorkingOnClient($_client) {
  125. $count = ProClientWork::where('pro_id', $this->id)->where('client_id', $_client->id)->where('is_active', true)->count();
  126. return $count > 0;
  127. }
  128. public function canvasCustomItems($_key) {
  129. return ClientCanvasDataCustomItem::where('key', $_key)
  130. ->where('pro_id', $this->id)
  131. ->orderBy('label')
  132. ->get();
  133. }
  134. /**
  135. * @param $_start - YYYY-MM-DD
  136. * @param $_end - YYYY-MM-DD
  137. * @param string $_timezone - defaults to EASTERN
  138. * @param string $_availableBG - defaults to #00a
  139. * @param string $_unavailableBG - defaults to #a00
  140. * @return array
  141. * @throws Exception
  142. */
  143. public function getAvailabilityEvents($_start, $_end, $_timezone = 'EASTERN', $_availableBG = '#00a', $_unavailableBG = '#a00') {
  144. $_start .= ' 00:00:00';
  145. $_end .= ' 23:59:59';
  146. // get availability data
  147. $proGenAvail = ProGeneralAvailability
  148. ::where('is_cancelled', false)
  149. ->where('pro_id', $this->id)
  150. ->get();
  151. $proSpecAvail = ProSpecificAvailability
  152. ::where('is_cancelled', false)
  153. ->where('pro_id', $this->id)
  154. ->where(function ($query) use ($_start, $_end) {
  155. $query
  156. ->where(function ($query2) use ($_start, $_end) {
  157. $query2
  158. ->where('start_time', '>=', $_start)
  159. ->where('start_time', '<=', $_end);
  160. })
  161. ->orWhere(function ($query2) use ($_start, $_end) {
  162. $query2
  163. ->where('end_time', '>=', $_start)
  164. ->where('end_time', '<=', $_end);
  165. });
  166. })
  167. ->get();
  168. $proSpecUnavail = ProSpecificUnavailability
  169. ::where('is_cancelled', false)
  170. ->where('pro_id', $this->id)
  171. ->where(function ($query) use ($_start, $_end) {
  172. $query
  173. ->where(function ($query2) use ($_start, $_end) {
  174. $query2
  175. ->where('start_time', '>=', $_start)
  176. ->where('start_time', '<=', $_end);
  177. })
  178. ->orWhere(function ($query2) use ($_start, $_end) {
  179. $query2
  180. ->where('end_time', '>=', $_start)
  181. ->where('end_time', '<=', $_end);
  182. });
  183. })
  184. ->get();
  185. // default GA
  186. // if no gen avail, assume mon to fri, 9 to 7
  187. /*if (count($proGenAvail) === 0) {
  188. $dayNames = ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY'];
  189. foreach ($dayNames as $dayName) {
  190. $item = new \stdClass();
  191. $item->day_of_week = $dayName;
  192. $item->timezone = $_timezone;
  193. $item->start_time = '09:00:00';
  194. $item->end_time = '18:00:00';
  195. $proGenAvail->push($item);
  196. }
  197. }*/
  198. // create timeline
  199. $phpTZ = appTZtoPHPTZ($_timezone);
  200. $phpTZObject = new \DateTimeZone($phpTZ);
  201. $startDate = new \DateTime($_start, $phpTZObject);
  202. $endDate = new \DateTime($_end, $phpTZObject);
  203. $proTimeLine = new TimeLine($startDate, $endDate);
  204. // General availability
  205. $period = new \DatePeriod($startDate, \DateInterval::createFromDateString('1 day'), $endDate);
  206. $days = [];
  207. foreach ($period as $day) {
  208. $days[] = [
  209. "day" => strtoupper($day->format("l")), // SUNDAY, etc.
  210. "date" => $day->format("Y-m-d"), // 2020-10-04, etc.
  211. ];
  212. }
  213. foreach ($days as $day) {
  214. $proGenAvailForTheDay = $proGenAvail->filter(function ($record) use ($day) {
  215. return $record->day_of_week === $day["day"];
  216. });
  217. foreach ($proGenAvailForTheDay as $ga) {
  218. $gaStart = new \DateTime($day["date"], new \DateTimeZone(appTZtoPHPTZ($ga->timezone)));
  219. $parts = explode(":", $ga->start_time);
  220. $gaStart->setTime(intval($parts[0]), intval($parts[1]), intval($parts[2]));
  221. $gaStart->setTimezone($phpTZObject);
  222. $gaEnd = new \DateTime($day["date"], new \DateTimeZone(appTZtoPHPTZ($ga->timezone)));
  223. $parts = explode(":", $ga->end_time);
  224. $gaEnd->setTime(intval($parts[0]), intval($parts[1]), intval($parts[2]));
  225. $gaEnd->setTimezone($phpTZObject);
  226. $proTimeLine->addAvailability($gaStart, $gaEnd);
  227. }
  228. }
  229. // specific availability
  230. foreach ($proSpecAvail as $sa) {
  231. $saStart = new \DateTime($sa->start_time, new \DateTimeZone(appTZtoPHPTZ($sa->timezone)));
  232. $saStart->setTimezone($phpTZObject);
  233. $saEnd = new \DateTime($sa->end_time, new \DateTimeZone(appTZtoPHPTZ($sa->timezone)));
  234. $saEnd->setTimezone($phpTZObject);
  235. $proTimeLine->addAvailability($saStart, $saEnd);
  236. }
  237. // specific unavailability
  238. foreach ($proSpecUnavail as $sua) {
  239. $suaStart = new \DateTime($sua->start_time, new \DateTimeZone(appTZtoPHPTZ($sua->timezone)));
  240. $suaStart->setTimezone($phpTZObject);
  241. $suaEnd = new \DateTime($sua->end_time, new \DateTimeZone(appTZtoPHPTZ($sua->timezone)));
  242. $suaEnd->setTimezone($phpTZObject);
  243. $proTimeLine->removeAvailability($suaStart, $suaEnd);
  244. }
  245. $events = [];
  246. // availability
  247. foreach ($proTimeLine->getAvailable() as $item) {
  248. $eStart = new \DateTime('@' . $item->start);
  249. $eStart->setTimezone($phpTZObject);
  250. $eEnd = new \DateTime('@' . $item->end);
  251. $eEnd->setTimezone($phpTZObject);
  252. $events[] = [
  253. "type" => "availability",
  254. "start" => $eStart->format('Y-m-d H:i:s'),
  255. "end" => $eEnd->format('Y-m-d H:i:s'),
  256. "editable" => false,
  257. "backgroundColor" => $_availableBG
  258. ];
  259. }
  260. // unavailability
  261. foreach ($proTimeLine->getUnavailable() as $item) {
  262. $eStart = new \DateTime('@' . $item->start);
  263. $eStart->setTimezone($phpTZObject);
  264. $eEnd = new \DateTime('@' . $item->end);
  265. $eEnd->setTimezone($phpTZObject);
  266. $events[] = [
  267. "type" => "unavailability",
  268. "start" => $eStart->format('Y-m-d H:i:s'),
  269. "end" => $eEnd->format('Y-m-d H:i:s'),
  270. "editable" => false,
  271. "backgroundColor" => $_unavailableBG
  272. ];
  273. }
  274. return $events;
  275. }
  276. public function getMyClientIds($_search = false) {
  277. $clients = $this->getAccessibleClientsQuery($_search)->get();
  278. $clientIds = [];
  279. foreach($clients as $client){
  280. $clientIds[] = $client->id;
  281. }
  282. return $clientIds;
  283. }
  284. public function favoritesByCategory($_category) {
  285. return ProFavorite::where('pro_id', $this->id)
  286. ->where('is_removed', false)
  287. ->where('category', $_category)
  288. ->orderBy('category', 'asc')
  289. ->orderBy('position_index', 'asc')
  290. ->get();
  291. }
  292. function get_patients_count_as_mcp() {
  293. $query = Client::whereNull('shadow_pro_id');
  294. return $query->where('mcp_pro_id', $this->id)->count();
  295. }
  296. function get_patients_count_as_dna() {
  297. $query = Client::whereNull('shadow_pro_id');
  298. return $query->where('default_na_pro_id', $this->id)->count();
  299. }
  300. function get_new_patients_awaiting_visit_count_as_mcp() {
  301. $query = Client::whereNull('shadow_pro_id');
  302. return $query->where('mcp_pro_id', $this->id)
  303. ->where('has_mcp_done_onboarding_visit', '!=', 'YES')
  304. ->count();
  305. }
  306. function get_new_patients_awaiting_visit_count_as_dna() {
  307. $query = Client::whereNull('shadow_pro_id');
  308. return $query->where('default_na_pro_id', $this->id)
  309. ->where('has_mcp_done_onboarding_visit', '!=', 'YES')
  310. ->count();
  311. }
  312. function get_notes_pending_signature_count_as_mcp() {
  313. return Note::where('hcp_pro_id', $this->id)
  314. ->where('is_cancelled', '<>', true)
  315. ->where('is_core_note', '<>', true)
  316. ->where('is_signed_by_hcp', '<>', true)
  317. ->count();
  318. }
  319. function get_notes_pending_signature_count_as_dna() {
  320. return Note::where('ally_pro_id', $this->id)
  321. ->where('is_cancelled', '<>', true)
  322. ->where('is_core_note', '<>', true)
  323. ->where('is_signed_by_ally', '<>', true)
  324. ->count();
  325. }
  326. function get_notes_pending_billing_count_as_mcp() {
  327. return Note::where('hcp_pro_id', $this->id)
  328. ->where('is_cancelled', '<>', true)
  329. ->where('is_signed_by_hcp', true)
  330. ->where('is_billing_marked_done', '<>', true)
  331. ->count();
  332. }
  333. function get_measurements_awaiting_review_count_as_mcp() {
  334. $result = DB::select(DB::raw("
  335. SELECT SUM(rm_num_measurements_not_stamped_by_mcp) AS count
  336. FROM care_month
  337. WHERE mcp_pro_id = :pro_id
  338. AND rm_num_measurements_not_stamped_by_mcp IS NOT NULL
  339. AND rm_num_measurements_not_stamped_by_mcp > 0;
  340. "), ["pro_id" => $this->id]);
  341. if($result) return $result[0]->count;
  342. }
  343. function get_bills_pending_signature_count_as_mcp(){
  344. return;
  345. $pendingBillsToSign = Bill::where('bill_service_type', '<>', 'CARE_MONTH')->where(function ($query) use ($performerProID) {
  346. $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_cancelled', false);
  347. })
  348. ->orWhere(function ($query) use ($performerProID) {
  349. $query->where('cm_pro_id', $performerProID)->where('is_signed_by_cm', false)->where('is_cancelled', false);;
  350. })->orWhere(function ($query) use ($performerProID) {
  351. $query->where('rme_pro_id', $performerProID)->where('is_signed_by_rme', false)->where('is_cancelled', false);;
  352. })->orWhere(function ($query) use ($performerProID) {
  353. $query->where('rmm_pro_id', $performerProID)->where('is_signed_by_rmm', false)->where('is_cancelled', false);;
  354. })->count();
  355. $keyNumbers['pendingBillsToSign'] = $pendingBillsToSign;
  356. }
  357. function get_incoming_reports_pending_signature_count_as_mcp() {
  358. return IncomingReport::where('hcp_pro_id', $this->id)
  359. ->where('has_hcp_pro_signed', '<>', true)
  360. ->where('is_entry_error', '<>', true)
  361. ->count();
  362. }
  363. function get_patients_without_appointment_query() {
  364. return Client::where('mcp_pro_id', $this->id)
  365. ->whereNull('today_mcp_appointment_date')
  366. ->where(function($q){
  367. $q->whereNull('next_mcp_appointment_id')
  368. ->orWhere('next_mcp_appointment_date', '<=', DB::raw('NOW()::DATE'));
  369. });
  370. }
  371. function get_patients_without_appointment_for_dna_query() {
  372. return Client::where('default_na_pro_id', $this->id)
  373. ->whereNull('today_mcp_appointment_date')
  374. ->where(function($q){
  375. $q->whereNull('next_mcp_appointment_id')
  376. ->orWhere('next_mcp_appointment_date', '<=', DB::raw('NOW()::DATE'));
  377. });
  378. }
  379. function get_patients_without_appointment_count_as_mcp() {
  380. return $this->get_patients_without_appointment_query()->count();
  381. }
  382. function get_patients_without_appointment_count_as_dna() {
  383. return $this->get_patients_without_appointment_for_dna_query()->count();
  384. }
  385. function get_patients_overdue_for_visit_query() {
  386. return Client::where('mcp_pro_id', $this->id)
  387. ->where(function($q){
  388. $q->whereNull('most_recent_completed_mcp_note_id')
  389. ->orWhere('most_recent_completed_mcp_note_date', '<', DB::raw("NOW()::DATE - INTERVAL '45 DAY'"));
  390. });
  391. }
  392. function get_patients_overdue_for_visit_for_dna_query() {
  393. return Client::where('default_na_pro_id', $this->id)
  394. ->where(function($q){
  395. $q->whereNull('most_recent_completed_mcp_note_id')
  396. ->orWhere('most_recent_completed_mcp_note_date', '<', DB::raw("NOW()::DATE - INTERVAL '45 DAY'"));
  397. });
  398. }
  399. function get_patients_overdue_count_as_mcp() {
  400. return $this->get_patients_overdue_for_visit_query()->count();
  401. }
  402. function get_patients_overdue_count_as_dna() {
  403. return $this->get_patients_overdue_for_visit_for_dna_query()->count();
  404. }
  405. function get_patients_without_remote_measurement_in_48_hours_count_as_mcp() {
  406. 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;
  407. }
  408. function get_patients_without_remote_measurement_in_48_hours_count_as_dna() {
  409. 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.default_na_pro_id = :default_na_pro_id AND is_active IS TRUE", ['default_na_pro_id'=>$this->id])[0]->count;
  410. }
  411. function get_cancelled_appointments_pending_acknowledgement_count_as_mcp_query() {
  412. // SELECT * FROM appointment WHERE hcp_pro_id = :me.id AND status = 'REJECTED' AND wasAcknowledgedByAppointmentPro IS NOT TRUE;
  413. return Appointment::where('pro_id', $this->id)
  414. ->where('latest_confirmation_decision_enum', 'REJECTED')
  415. ->where('is_decision_acknowledgement_from_appointment_pro_pending', true);
  416. }
  417. function get_cancelled_appointments_pending_acknowledgement_count_as_mcp() {
  418. // SELECT * FROM appointment WHERE hcp_pro_id = :me.id AND status = 'REJECTED' AND wasAcknowledgedByAppointmentPro IS NOT TRUE;
  419. return $this->get_cancelled_appointments_pending_acknowledgement_count_as_mcp_query()->count();
  420. }
  421. function get_cancelled_bills_awaiting_review_count_as_mcp() {
  422. // SELECT * FROM bill WHERE bill_service_type = 'NOTE' AND is_cancelled IS TRUE AND isCancellationAcknowledged IS FALSE;
  423. return Bill::where('hcp_pro_id', $this->id)
  424. ->where('bill_service_type', 'NOTE')
  425. ->where('is_cancelled', true)
  426. ->where('is_cancellation_acknowledged', '<>', true)
  427. ->count();
  428. }
  429. //TODO: Generic bills that are cancelled where performer is the pro and not acknowledged
  430. function get_cancelled_bills_awaiting_review_count_as_dna() {
  431. // SELECT * FROM bill WHERE bill_service_type = 'GENERIC' AND is_cancelled IS TRUE AND isCancellationAcknowledged IS FALSE;
  432. return Bill::where('generic_pro_id', $this->id)
  433. ->where('bill_service_type', 'GENERIC')
  434. ->where('is_cancelled', true)
  435. ->where('is_cancellation_acknowledged', '<>', true)
  436. ->count();
  437. }
  438. function get_cancelled_supply_orders_awaiting_review_count_as_mcp() {
  439. // SELECT * FROM supply_order WHERE signed_by_pro_id = :me.id AND is_cancelled IS TRUE AND isCancellationAcknowledged IS NOT TRUE;
  440. return SupplyOrder::where('signed_by_pro_id', $this->id)
  441. ->where('is_cancelled', true)
  442. ->where('is_cancellation_acknowledged', '<>', true)
  443. ->count();
  444. }
  445. function get_erx_and_orders_awaiting_signature_count_as_mcp() {
  446. // SELECT * FROM erx WHERE hcp_pro_id = :me.id AND pro_declared_status <> 'CANCELLED' AND hasHcpProSigned IS NOT TRUE;
  447. return Erx::where('hcp_pro_id', $this->id)
  448. ->where('pro_declared_status', '<>', 'CANCELLED')
  449. ->where('has_hcp_pro_signed', '<>', true)
  450. ->count();
  451. }
  452. function get_supply_orders_awaiting_signature_count_as_mcp() {
  453. // 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;
  454. return SupplyOrder::where('created_by_pro_id', $this->id)
  455. ->whereNull('signed_by_pro_id')
  456. ->where('is_cancelled', '<>', true)
  457. ->count();
  458. }
  459. function get_supply_orders_awaiting_shipment_count_as_mcp() {
  460. return SupplyOrder::where('created_by_pro_id', $this->id)
  461. ->where('is_signed_by_pro', true)
  462. ->where('is_cleared_for_shipment', true)
  463. ->whereNull('shipment_id')
  464. ->count();
  465. }
  466. function get_birthdays_today_as_mcp(){
  467. return;
  468. $queryClients = $this->performer()->pro->getAccessibleClientsQuery();
  469. $keyNumbers['patientsHavingBirthdayToday'] = $queryClients
  470. ->whereRaw('EXTRACT(DAY from dob) = ?', [date('d')])
  471. ->whereRaw('EXTRACT(MONTH from dob) = ?', [date('m')])
  472. ->count();
  473. $reimbursement = [];
  474. $reimbursement["currentBalance"] = $performer->pro->balance;
  475. $reimbursement["nextPaymentDate"] = '--';
  476. $lastPayment = ProTransaction::where('pro_id', $performerProID)->where('plus_or_minus', 'PLUS')->orderBy('created_at', 'DESC')->first();
  477. if ($lastPayment) {
  478. $reimbursement["lastPayment"] = $lastPayment->amount;
  479. $reimbursement["lastPaymentDate"] = $lastPayment->created_at;
  480. } else {
  481. $reimbursement["lastPayment"] = '--';
  482. $reimbursement["lastPaymentDate"] = '--';
  483. }
  484. }
  485. public function getAppointmentsPendingStatusChangeAck() {
  486. return Appointment::where('pro_id', $this->id)
  487. ->where('is_status_acknowledgement_from_appointment_pro_pending', true)
  488. ->where('raw_date', '>=', DB::raw('NOW()'))
  489. ->orderBy('raw_date', 'asc')
  490. ->get();
  491. }
  492. public function getAppointmentsPendingDecisionAck() {
  493. return Appointment::where('pro_id', $this->id)
  494. ->where('is_decision_acknowledgement_from_appointment_pro_pending', true)
  495. ->where('raw_date', '>=', DB::raw('NOW()'))
  496. ->orderBy('raw_date', 'asc')
  497. ->get();
  498. }
  499. public function getAppointmentsPendingTimeChangeAck() {
  500. return Appointment::where('pro_id', $this->id)
  501. ->where('is_time_change_acknowledgement_from_appointment_pro_pending', true)
  502. ->where('raw_date', '>=', DB::raw('NOW()'))
  503. ->orderBy('raw_date', 'asc')
  504. ->get();
  505. }
  506. public function getAccessibleClientsQuery($_search = false) {
  507. $proID = $this->id;
  508. $query = Client::whereNull('shadow_pro_id');
  509. if ($this->pro_type === 'ADMIN' && ($_search ? $this->can_see_any_client_via_search : $this->can_see_all_clients_in_list)) {
  510. $query = $query->where('id', '>', 0);
  511. } else {
  512. $query = $query->where(function ($q) use ($proID) {
  513. $q->where('mcp_pro_id', $proID)
  514. ->orWhere('cm_pro_id', $proID)
  515. ->orWhere('rmm_pro_id', $proID)
  516. ->orWhere('rme_pro_id', $proID)
  517. ->orWhere('physician_pro_id', $proID)
  518. ->orWhere('default_na_pro_id', $proID)
  519. ->orWhereRaw('id IN (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = ?)', [$proID])
  520. ->orWhereRaw('id IN (SELECT client_id FROM appointment WHERE status NOT IN (\'CANCELLED\') AND pro_id = ?)', [$proID])
  521. ->orWhereRaw('id IN (SELECT mcp_pro_id FROM client_program WHERE client_id = client.id AND is_active = TRUE)')
  522. ->orWhereRaw('id IN (SELECT manager_pro_id FROM client_program WHERE client_id = client.id AND is_active = TRUE)')
  523. ->orWhereRaw('id IN (SELECT client_id FROM note WHERE ally_pro_id = ? AND is_cancelled = FALSE)', [$proID]);;
  524. });
  525. }
  526. return $query;
  527. }
  528. public function canAccess($_patientUid) {
  529. $proID = $this->id;
  530. if ($this->pro_type === 'ADMIN') {
  531. return true;
  532. }
  533. $canAccess = Client::select('uid')
  534. ->where('uid', $_patientUid)
  535. ->where(function ($q) use ($proID) {
  536. $q->where('mcp_pro_id', $proID)
  537. ->orWhere('cm_pro_id', $proID)
  538. ->orWhere('rmm_pro_id', $proID)
  539. ->orWhere('rme_pro_id', $proID)
  540. ->orWhere('physician_pro_id', $proID)
  541. ->orWhere('default_na_pro_id', $proID)
  542. ->orWhereRaw('id IN (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = ?)', [$proID])
  543. ->orWhereRaw('id IN (SELECT client_id FROM appointment WHERE status NOT IN (\'CANCELLED\') AND pro_id = ?)', [$proID])
  544. ->orWhereRaw('id IN (SELECT mcp_pro_id FROM client_program WHERE client_id = client.id AND is_active = TRUE)')
  545. ->orWhereRaw('id IN (SELECT manager_pro_id FROM client_program WHERE client_id = client.id AND is_active = TRUE)')
  546. ->orWhereRaw('id IN (SELECT client_id FROM note WHERE ally_pro_id = ? AND is_cancelled = FALSE)', [$proID]);
  547. })->count();
  548. return !!$canAccess;
  549. }
  550. public function canAddCPMEntryForMeasurement(Measurement $measurement, Pro $pro)
  551. {
  552. // check if client has any programs where this measurement type is allowed
  553. $allowed = false;
  554. $client = $measurement->client;
  555. $clientPrograms = $client->clientPrograms;
  556. if($pro->pro_type !== 'ADMIN') {
  557. $clientPrograms = $clientPrograms->filter(function($_clientProgram) use ($pro) {
  558. return $_clientProgram->manager_pro_id === $pro->id;
  559. });
  560. }
  561. if(count($clientPrograms)) {
  562. foreach ($clientPrograms as $clientProgram) {
  563. if(strpos(strtolower($clientProgram->measurement_labels), '|' . strtolower($measurement->label) . '|') !== FALSE) {
  564. $allowed = true;
  565. break;
  566. }
  567. }
  568. }
  569. return $allowed ? $clientPrograms : FALSE;
  570. }
  571. public function getUnstampedMeasurementsFromCurrentMonth($_countOnly, $skip, $limit)
  572. {
  573. date_default_timezone_set('US/Eastern');
  574. $start = strtotime(date('Y-m-01'));
  575. $end = date_add(date_create(date('Y-m-01')), date_interval_create_from_date_string("1 month"))->getTimestamp();
  576. $start *= 1000;
  577. $end *= 1000;
  578. $measurementsQuery = Measurement::where('is_removed', false)
  579. ->join('client', 'client.id', '=', 'measurement.client_id')
  580. ->whereNotNull('measurement.client_bdt_measurement_id')
  581. ->whereNotNull('measurement.ts')
  582. ->where('measurement.is_cellular_zero', false)
  583. ->where('measurement.ts', '>=', $start)
  584. ->where('measurement.ts', '<', $end)
  585. ->whereIn('measurement.client_id', $this->getMyClientIds())
  586. ->where(function ($q) {
  587. $q
  588. ->where(function ($q2) {
  589. $q2
  590. ->where('client.mcp_pro_id', $this->id)
  591. ->where('measurement.has_been_stamped_by_mcp', false);
  592. })
  593. ->orWhere(function ($q2) {
  594. $q2
  595. ->where('client.default_na_pro_id', $this->id)
  596. ->where('measurement.has_been_stamped_by_non_hcp', false);
  597. })
  598. ->orWhere(function ($q2) {
  599. $q2
  600. ->where('client.rmm_pro_id', $this->id)
  601. ->where('measurement.has_been_stamped_by_rmm', false);
  602. })
  603. ->orWhere(function ($q2) {
  604. $q2
  605. ->where('client.rme_pro_id', $this->id)
  606. ->where('measurement.has_been_stamped_by_rme', false);
  607. });
  608. });
  609. if($_countOnly) {
  610. return $measurementsQuery->count();
  611. }
  612. $x = [];
  613. $measurements = $measurementsQuery
  614. ->orderBy('ts', 'desc')
  615. ->skip($skip)
  616. ->take($limit)
  617. ->get();
  618. // eager load stuff needed in JS
  619. foreach ($measurements as $measurement) {
  620. // if ($measurement->client_bdt_measurement_id) {
  621. // $measurement->bdtMeasurement = $measurement->clientBDTMeasurement->measurement;
  622. // }
  623. unset($measurement->clientBDTMeasurement); // we do not need this travelling to the frontend
  624. $client = [
  625. "uid" => $measurement->client->uid,
  626. "name" => $measurement->client->displayName(),
  627. ];
  628. $measurement->patient = $client;
  629. $measurement->careMonth = $measurement->client->currentCareMonth();
  630. $measurement->timestamp = friendlier_date_time($measurement->created_at);
  631. unset($measurement->client); // we do not need this travelling to the frontend
  632. if(@$measurement->detail_json) unset($measurement->detail_json);
  633. if(@$measurement->canvas_data) unset($measurement->canvas_data);
  634. if(@$measurement->latest_measurements) unset($measurement->latest_measurements);
  635. if(@$measurement->info_lines) unset($measurement->info_lines);
  636. if(@$measurement->canvas_data_backup) unset($measurement->canvas_data_backup);
  637. if(@$measurement->migrated_canvas_data_backup) unset($measurement->migrated_canvas_data_backup);
  638. // if($measurement->label == 'SBP' || $measurement->label = 'DBP'){
  639. // continue;
  640. // }
  641. $x[] = $measurement;
  642. }
  643. // dd($measurements);
  644. return $measurements;
  645. }
  646. public function getMeasurements($_onlyUnstamped = true)
  647. {
  648. $measurementsQuery = Measurement::where('is_removed', false);
  649. if ($this->pro_type != 'ADMIN') {
  650. $measurementsQuery
  651. ->whereIn('client_id', $this->getMyClientIds());
  652. }
  653. if ($_onlyUnstamped) {
  654. $measurementsQuery
  655. ->whereNotNull('client_bdt_measurement_id')
  656. ->whereNotNull('ts')
  657. ->where('is_cellular_zero', false)
  658. ->where(function ($q) {
  659. $q->whereNull('status')
  660. ->orWhere(function ($q2) {
  661. $q2->where('status', '<>', 'ACK')
  662. ->where('status', '<>', 'INVALID_ACK');
  663. });
  664. });
  665. }
  666. $x = [];
  667. $measurements = $measurementsQuery->orderBy('ts', 'desc')->paginate(50);
  668. // eager load stuff needed in JS
  669. foreach ($measurements as $measurement) {
  670. // if ($measurement->client_bdt_measurement_id) {
  671. // $measurement->bdtMeasurement = $measurement->clientBDTMeasurement->measurement;
  672. // }
  673. unset($measurement->clientBDTMeasurement); // we do not need this travelling to the frontend
  674. $client = [
  675. "uid" => $measurement->client->uid,
  676. "name" => $measurement->client->displayName(),
  677. ];
  678. $measurement->patient = $client;
  679. $measurement->careMonth = $measurement->client->currentCareMonth();
  680. $measurement->timestamp = friendly_date_time($measurement->created_at);
  681. unset($measurement->client); // we do not need this travelling to the frontend
  682. // if($measurement->label == 'SBP' || $measurement->label = 'DBP'){
  683. // continue;
  684. // }
  685. $x[] = $measurement;
  686. }
  687. return $measurements;
  688. }
  689. public function companyPros()
  690. {
  691. return $this->hasMany(CompanyPro::class, 'pro_id', 'id')
  692. ->where('is_active', true);
  693. }
  694. public function companyProPayers()
  695. {
  696. return $this->hasMany(CompanyProPayer::class, 'pro_id', 'id');
  697. }
  698. public function isAssociatedWithMCPayer() {
  699. $companyProPayers = $this->companyProPayers;
  700. $foundMC = false;
  701. if($companyProPayers) {
  702. foreach ($companyProPayers as $companyProPayer) {
  703. if($companyProPayer->payer && $companyProPayer->payer->is_medicare) {
  704. $foundMC = true;
  705. break;
  706. }
  707. }
  708. }
  709. return $foundMC;
  710. }
  711. public function isAssociatedWithNonMCPayer($_payerID) {
  712. $companyProPayers = $this->companyProPayers;
  713. $foundNonMC = false;
  714. if($companyProPayers) {
  715. foreach ($companyProPayers as $companyProPayer) {
  716. if($companyProPayer->payer && !$companyProPayer->payer->is_medicare && $companyProPayer->payer->id === $_payerID) {
  717. $foundNonMC = true;
  718. break;
  719. }
  720. }
  721. }
  722. return $foundNonMC;
  723. }
  724. public function companyLocations() {
  725. $companyProPayers = $this->companyProPayers;
  726. $companyIDs = [];
  727. foreach ($companyProPayers as $companyProPayer) {
  728. $companyIDs[] = $companyProPayer->company_id;
  729. }
  730. $locations = [];
  731. if(count($companyIDs)) {
  732. $locations = CompanyLocation::whereIn('id', $companyIDs)->get();
  733. }
  734. return $locations;
  735. }
  736. public function shadowClient() {
  737. return $this->hasOne(Client::class, 'id', 'shadow_client_id');
  738. }
  739. public function defaultCompanyPro() {
  740. return $this->hasOne(CompanyPro::class, 'id', 'default_company_pro_id');
  741. }
  742. public function currentNotePickupForProcessing() {
  743. return $this->hasOne(NotePickupForProcessing::class, 'id', 'current_note_pickup_for_processing_id');
  744. }
  745. public function get_patients_not_seen_in_45_days_count_as_mcp(){
  746. return 0;
  747. }
  748. //DNA_DASHBOARD
  749. //queries
  750. private function patientsQueryAsDna(){
  751. // WHERE na_pro_id = :me.id
  752. return Client::where('default_na_pro_id', $this->id);
  753. }
  754. private function patientsAwaitingMcpVisitQueryAsDna(){
  755. // WHERE has_mcp_done_onboarding_visit <> 'YES'
  756. return Client::where('default_na_pro_id', $this->id)->where('has_mcp_done_onboarding_visit', '<>', 'YES');
  757. }
  758. private function patientsWithoutAppointmentQueryAsDna(){
  759. // WHERE today_mcp_appointment_date IS NULL AND next_mcp_appointment_date IS NULL
  760. return Client::where('default_na_pro_id', $this->id)
  761. ->whereNull('today_mcp_appointment_date')
  762. ->whereNull('next_mcp_appointment_date');
  763. }
  764. private function encountersPendingMyReviewQueryAsDna(){
  765. // 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;
  766. return Note::where('ally_pro_id', $this->id)
  767. ->where('is_cancelled', '<>', true)
  768. ->where('is_signed_by_hcp', true)
  769. ->where('is_signed_by_ally','<>', true);
  770. }
  771. private function encountersInProgressQueryAsDna(){
  772. // 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;
  773. return Note::where('ally_pro_id', $this->id)
  774. ->where('is_cancelled', '<>', true)
  775. ->where('is_signed_by_hcp', '<>', true);
  776. }
  777. private function appointmentsPendingConfirmationQueryAsDna(){
  778. // WHERE client_id IN (SELECT id FROM client WHERE default_na_pro_id = :me.id) AND status = 'PENDING'
  779. $myId = $this->id;
  780. return Appointment::whereHas('client', function($clientQuery) use ($myId) {
  781. return $clientQuery->where('default_na_pro_id', $myId);
  782. })->where('status', 'PENDING');
  783. }
  784. private function cancelledAppointmentsPendingAckQueryAsDna(){
  785. // 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;
  786. $myId = $this->id;
  787. return Appointment::whereHas('client', function($clientQuery) use ($myId) {
  788. return $clientQuery->where('default_na_pro_id', $myId);
  789. })->where('status', 'CANCELLED')
  790. ->where('is_status_acknowledgement_from_default_na_pending', true);
  791. }
  792. private function reportsPendingAckQueryAsDna(){
  793. // 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
  794. $myId = $this->id;
  795. return IncomingReport::whereHas('client',function($clientQuery) use ($myId) {
  796. return $clientQuery->where('default_na_pro_id', $myId);
  797. })->where('has_na_pro_signed', '<>', true)
  798. ->where('is_entry_error','<>', true);
  799. }
  800. private function supplyOrdersPendingMyAckQueryAsDna(){
  801. // 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;
  802. $myId = $this->id;
  803. return SupplyOrder::whereHas('client',function($clientQuery) use ($myId) {
  804. return $clientQuery->where('default_na_pro_id', $myId);
  805. })->where('has_na_pro_signed', '<>', true)
  806. ->where('is_signed_by_pro', true)
  807. ->where('is_cancelled', '<>', true);
  808. }
  809. private function supplyOrdersPendingHcpApprovalQueryAsDna(){
  810. // 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;
  811. $myId = $this->id;
  812. return SupplyOrder::whereHas('client',function($clientQuery) use ($myId) {
  813. return $clientQuery->where('default_na_pro_id', $myId);
  814. })->where('has_na_pro_signed', true)
  815. ->where('is_signed_by_pro','<>', true)
  816. ->where('is_cancelled', '<>', true);
  817. }
  818. //counts
  819. public function patientsCountAsDna(){
  820. return $this->patientsQueryAsDna()->count();
  821. }
  822. public function patientsAwaitingMcpVisitCountAsDna(){
  823. return $this->patientsAwaitingMcpVisitQueryAsDna()->count();
  824. }
  825. public function patientsWithoutAppointmentCountAsDna(){
  826. return $this->patientsWithoutAppointmentQueryAsDna()->count();
  827. }
  828. public function encountersPendingMyReviewCountAsDna(){
  829. return $this->encountersPendingMyReviewQueryAsDna()->count();
  830. }
  831. public function encountersInProgressCountAsDna(){
  832. return $this->encountersInProgressQueryAsDna()->count();
  833. }
  834. public function appointmentsPendingConfirmationCountAsDna(){
  835. return $this->appointmentsPendingConfirmationQueryAsDna()->count();
  836. }
  837. public function cancelledAppointmentsPendingAckCountAsDna(){
  838. return $this->cancelledAppointmentsPendingAckQueryAsDna()->count();
  839. }
  840. public function reportsPendingAckCountAsDna(){
  841. return $this->reportsPendingAckQueryAsDna()->count();
  842. }
  843. public function supplyOrdersPendingMyAckCountAsDna(){
  844. return $this->supplyOrdersPendingMyAckQueryAsDna()->count();
  845. }
  846. public function supplyOrdersPendingHcpApprovalCountAsDna(){
  847. return $this->supplyOrdersPendingHcpApprovalQueryAsDna()->count();
  848. }
  849. //records
  850. private $DNA_RESULTS_PAGE_SIZE = 50;
  851. public function patientsRecordsAsDna(){
  852. return $this->patientsQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  853. }
  854. public function patientsAwaitingMcpVisitRecordsAsDna(){
  855. return $this->patientsAwaitingMcpVisitQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  856. }
  857. public function patientsWithoutAppointmentRecordsAsDna(){
  858. return $this->patientsWithoutAppointmentQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  859. }
  860. public function encountersPendingMyReviewRecordsAsDna(){
  861. return $this->encountersPendingMyReviewQueryAsDna()
  862. ->orderBy('effective_dateest', 'desc')
  863. ->orderBy('created_at', 'desc')
  864. ->paginate($this->DNA_RESULTS_PAGE_SIZE);
  865. }
  866. public function encountersInProgressRecordsAsDna(){
  867. return $this->encountersInProgressQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  868. }
  869. public function appointmentsPendingConfirmationRecordsAsDna(){
  870. return $this->appointmentsPendingConfirmationQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  871. }
  872. public function cancelledAppointmentsPendingAckRecordsAsDna(){
  873. return $this->cancelledAppointmentsPendingAckQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  874. }
  875. public function reportsPendingAckRecordsAsDna(){
  876. return $this->reportsPendingAckQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  877. }
  878. public function supplyOrdersPendingMyAckRecordsAsDna(){
  879. return $this->supplyOrdersPendingMyAckQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  880. }
  881. public function supplyOrdersPendingHcpApprovalRecordsAsDna(){
  882. return $this->supplyOrdersPendingHcpApprovalQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  883. }
  884. }