Pro.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857
  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. }
  407. function get_patients_without_remote_measurement_in_48_hours_count_as_dna() {
  408. }
  409. function get_cancelled_appointments_pending_acknowledgement_count_as_mcp_query() {
  410. // SELECT * FROM appointment WHERE hcp_pro_id = :me.id AND status = 'REJECTED' AND wasAcknowledgedByAppointmentPro IS NOT TRUE;
  411. return Appointment::where('pro_id', $this->id)
  412. ->where('latest_confirmation_decision_enum', 'REJECTED')
  413. ->where('is_decision_acknowledgement_from_appointment_pro_pending', true);
  414. }
  415. function get_cancelled_appointments_pending_acknowledgement_count_as_mcp() {
  416. // SELECT * FROM appointment WHERE hcp_pro_id = :me.id AND status = 'REJECTED' AND wasAcknowledgedByAppointmentPro IS NOT TRUE;
  417. return $this->get_cancelled_appointments_pending_acknowledgement_count_as_mcp_query()->count();
  418. }
  419. function get_cancelled_bills_awaiting_review_count_as_mcp() {
  420. // SELECT * FROM bill WHERE bill_service_type = 'NOTE' AND is_cancelled IS TRUE AND isCancellationAcknowledged IS FALSE;
  421. return Bill::where('hcp_pro_id', $this->id)
  422. ->where('bill_service_type', 'NOTE')
  423. ->where('is_cancelled', true)
  424. ->where('is_cancellation_acknowledged', '<>', true)
  425. ->count();
  426. }
  427. //TODO: Generic bills that are cancelled where performer is the pro and not acknowledged
  428. function get_cancelled_bills_awaiting_review_count_as_dna() {
  429. // SELECT * FROM bill WHERE bill_service_type = 'GENERIC' AND is_cancelled IS TRUE AND isCancellationAcknowledged IS FALSE;
  430. return Bill::where('generic_pro_id', $this->id)
  431. ->where('bill_service_type', 'GENERIC')
  432. ->where('is_cancelled', true)
  433. ->where('is_cancellation_acknowledged', '<>', true)
  434. ->count();
  435. }
  436. function get_cancelled_supply_orders_awaiting_review_count_as_mcp() {
  437. // SELECT * FROM supply_order WHERE signed_by_pro_id = :me.id AND is_cancelled IS TRUE AND isCancellationAcknowledged IS NOT TRUE;
  438. return SupplyOrder::where('signed_by_pro_id', $this->id)
  439. ->where('is_cancelled', true)
  440. ->where('is_cancellation_acknowledged', '<>', true)
  441. ->count();
  442. }
  443. function get_erx_and_orders_awaiting_signature_count_as_mcp() {
  444. // SELECT * FROM erx WHERE hcp_pro_id = :me.id AND pro_declared_status <> 'CANCELLED' AND hasHcpProSigned IS NOT TRUE;
  445. return Erx::where('hcp_pro_id', $this->id)
  446. ->where('pro_declared_status', '<>', 'CANCELLED')
  447. ->where('has_hcp_pro_signed', '<>', true)
  448. ->count();
  449. }
  450. function get_supply_orders_awaiting_signature_count_as_mcp() {
  451. // 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;
  452. return SupplyOrder::where('created_by_pro_id', $this->id)
  453. ->whereNull('signed_by_pro_id')
  454. ->where('is_cancelled', '<>', true)
  455. ->count();
  456. }
  457. function get_supply_orders_awaiting_shipment_count_as_mcp() {
  458. return SupplyOrder::where('created_by_pro_id', $this->id)
  459. ->where('is_signed_by_pro', true)
  460. ->where('is_cleared_for_shipment', true)
  461. ->whereNull('shipment_id')
  462. ->count();
  463. }
  464. function get_birthdays_today_as_mcp(){
  465. return;
  466. $queryClients = $this->performer()->pro->getAccessibleClientsQuery();
  467. $keyNumbers['patientsHavingBirthdayToday'] = $queryClients
  468. ->whereRaw('EXTRACT(DAY from dob) = ?', [date('d')])
  469. ->whereRaw('EXTRACT(MONTH from dob) = ?', [date('m')])
  470. ->count();
  471. $reimbursement = [];
  472. $reimbursement["currentBalance"] = $performer->pro->balance;
  473. $reimbursement["nextPaymentDate"] = '--';
  474. $lastPayment = ProTransaction::where('pro_id', $performerProID)->where('plus_or_minus', 'PLUS')->orderBy('created_at', 'DESC')->first();
  475. if ($lastPayment) {
  476. $reimbursement["lastPayment"] = $lastPayment->amount;
  477. $reimbursement["lastPaymentDate"] = $lastPayment->created_at;
  478. } else {
  479. $reimbursement["lastPayment"] = '--';
  480. $reimbursement["lastPaymentDate"] = '--';
  481. }
  482. }
  483. public function getAppointmentsPendingStatusChangeAck() {
  484. return Appointment::where('pro_id', $this->id)
  485. ->where('is_status_acknowledgement_from_appointment_pro_pending', true)
  486. ->where('raw_date', '>=', DB::raw('NOW()'))
  487. ->orderBy('raw_date', 'asc')
  488. ->get();
  489. }
  490. public function getAppointmentsPendingDecisionAck() {
  491. return Appointment::where('pro_id', $this->id)
  492. ->where('is_decision_acknowledgement_from_appointment_pro_pending', true)
  493. ->where('raw_date', '>=', DB::raw('NOW()'))
  494. ->orderBy('raw_date', 'asc')
  495. ->get();
  496. }
  497. public function getAppointmentsPendingTimeChangeAck() {
  498. return Appointment::where('pro_id', $this->id)
  499. ->where('is_time_change_acknowledgement_from_appointment_pro_pending', true)
  500. ->where('raw_date', '>=', DB::raw('NOW()'))
  501. ->orderBy('raw_date', 'asc')
  502. ->get();
  503. }
  504. public function getAccessibleClientsQuery($_search = false) {
  505. $proID = $this->id;
  506. $query = Client::whereNull('shadow_pro_id');
  507. if ($this->pro_type === 'ADMIN' && ($_search ? $this->can_see_any_client_via_search : $this->can_see_all_clients_in_list)) {
  508. $query = $query->where('id', '>', 0);
  509. } else {
  510. $query = $query->where(function ($q) use ($proID) {
  511. $q->where('mcp_pro_id', $proID)
  512. ->orWhere('cm_pro_id', $proID)
  513. ->orWhere('rmm_pro_id', $proID)
  514. ->orWhere('rme_pro_id', $proID)
  515. ->orWhere('physician_pro_id', $proID)
  516. ->orWhere('default_na_pro_id', $proID)
  517. ->orWhereRaw('id IN (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = ?)', [$proID])
  518. ->orWhereRaw('id IN (SELECT client_id FROM appointment WHERE status NOT IN (\'CANCELLED\') AND pro_id = ?)', [$proID])
  519. ->orWhereRaw('id IN (SELECT mcp_pro_id FROM client_program WHERE client_id = client.id AND is_active = TRUE)')
  520. ->orWhereRaw('id IN (SELECT manager_pro_id FROM client_program WHERE client_id = client.id AND is_active = TRUE)')
  521. ->orWhereRaw('id IN (SELECT client_id FROM note WHERE ally_pro_id = ? AND is_cancelled = FALSE)', [$proID]);;
  522. });
  523. }
  524. return $query;
  525. }
  526. public function canAccess($_patientUid) {
  527. $proID = $this->id;
  528. if ($this->pro_type === 'ADMIN') {
  529. return true;
  530. }
  531. $canAccess = Client::select('uid')
  532. ->where('uid', $_patientUid)
  533. ->where(function ($q) use ($proID) {
  534. $q->where('mcp_pro_id', $proID)
  535. ->orWhere('cm_pro_id', $proID)
  536. ->orWhere('rmm_pro_id', $proID)
  537. ->orWhere('rme_pro_id', $proID)
  538. ->orWhere('physician_pro_id', $proID)
  539. ->orWhere('default_na_pro_id', $proID)
  540. ->orWhereRaw('id IN (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = ?)', [$proID])
  541. ->orWhereRaw('id IN (SELECT client_id FROM appointment WHERE status NOT IN (\'CANCELLED\') AND pro_id = ?)', [$proID])
  542. ->orWhereRaw('id IN (SELECT mcp_pro_id FROM client_program WHERE client_id = client.id AND is_active = TRUE)')
  543. ->orWhereRaw('id IN (SELECT manager_pro_id FROM client_program WHERE client_id = client.id AND is_active = TRUE)')
  544. ->orWhereRaw('id IN (SELECT client_id FROM note WHERE ally_pro_id = ? AND is_cancelled = FALSE)', [$proID]);
  545. })->count();
  546. return !!$canAccess;
  547. }
  548. public function canAddCPMEntryForMeasurement(Measurement $measurement, Pro $pro)
  549. {
  550. // check if client has any programs where this measurement type is allowed
  551. $allowed = false;
  552. $client = $measurement->client;
  553. $clientPrograms = $client->clientPrograms;
  554. if($pro->pro_type !== 'ADMIN') {
  555. $clientPrograms = $clientPrograms->filter(function($_clientProgram) use ($pro) {
  556. return $_clientProgram->manager_pro_id === $pro->id;
  557. });
  558. }
  559. if(count($clientPrograms)) {
  560. foreach ($clientPrograms as $clientProgram) {
  561. if(strpos(strtolower($clientProgram->measurement_labels), '|' . strtolower($measurement->label) . '|') !== FALSE) {
  562. $allowed = true;
  563. break;
  564. }
  565. }
  566. }
  567. return $allowed ? $clientPrograms : FALSE;
  568. }
  569. public function getUnstampedMeasurementsFromCurrentMonth($_countOnly, $skip, $limit)
  570. {
  571. date_default_timezone_set('US/Eastern');
  572. $start = strtotime(date('Y-m-01'));
  573. $end = date_add(date_create(date('Y-m-01')), date_interval_create_from_date_string("1 month"))->getTimestamp();
  574. $start *= 1000;
  575. $end *= 1000;
  576. $measurementsQuery = Measurement::where('is_removed', false)
  577. ->join('client', 'client.id', '=', 'measurement.client_id')
  578. ->whereNotNull('measurement.client_bdt_measurement_id')
  579. ->whereNotNull('measurement.ts')
  580. ->where('measurement.is_cellular_zero', false)
  581. ->where('measurement.ts', '>=', $start)
  582. ->where('measurement.ts', '<', $end)
  583. ->whereIn('measurement.client_id', $this->getMyClientIds())
  584. ->where(function ($q) {
  585. $q
  586. ->where(function ($q2) {
  587. $q2
  588. ->where('client.mcp_pro_id', $this->id)
  589. ->where('measurement.has_been_stamped_by_mcp', false);
  590. })
  591. ->orWhere(function ($q2) {
  592. $q2
  593. ->where('client.default_na_pro_id', $this->id)
  594. ->where('measurement.has_been_stamped_by_non_hcp', false);
  595. })
  596. ->orWhere(function ($q2) {
  597. $q2
  598. ->where('client.rmm_pro_id', $this->id)
  599. ->where('measurement.has_been_stamped_by_rmm', false);
  600. })
  601. ->orWhere(function ($q2) {
  602. $q2
  603. ->where('client.rme_pro_id', $this->id)
  604. ->where('measurement.has_been_stamped_by_rme', false);
  605. });
  606. });
  607. if($_countOnly) {
  608. return $measurementsQuery->count();
  609. }
  610. $x = [];
  611. $measurements = $measurementsQuery
  612. ->orderBy('ts', 'desc')
  613. ->skip($skip)
  614. ->take($limit)
  615. ->get();
  616. // eager load stuff needed in JS
  617. foreach ($measurements as $measurement) {
  618. // if ($measurement->client_bdt_measurement_id) {
  619. // $measurement->bdtMeasurement = $measurement->clientBDTMeasurement->measurement;
  620. // }
  621. unset($measurement->clientBDTMeasurement); // we do not need this travelling to the frontend
  622. $client = [
  623. "uid" => $measurement->client->uid,
  624. "name" => $measurement->client->displayName(),
  625. ];
  626. $measurement->patient = $client;
  627. $measurement->careMonth = $measurement->client->currentCareMonth();
  628. $measurement->timestamp = friendlier_date_time($measurement->created_at);
  629. unset($measurement->client); // we do not need this travelling to the frontend
  630. if(@$measurement->detail_json) unset($measurement->detail_json);
  631. if(@$measurement->canvas_data) unset($measurement->canvas_data);
  632. if(@$measurement->latest_measurements) unset($measurement->latest_measurements);
  633. if(@$measurement->info_lines) unset($measurement->info_lines);
  634. if(@$measurement->canvas_data_backup) unset($measurement->canvas_data_backup);
  635. if(@$measurement->migrated_canvas_data_backup) unset($measurement->migrated_canvas_data_backup);
  636. // if($measurement->label == 'SBP' || $measurement->label = 'DBP'){
  637. // continue;
  638. // }
  639. $x[] = $measurement;
  640. }
  641. // dd($measurements);
  642. return $measurements;
  643. }
  644. public function getMeasurements($_onlyUnstamped = true)
  645. {
  646. $measurementsQuery = Measurement::where('is_removed', false);
  647. if ($this->pro_type != 'ADMIN') {
  648. $measurementsQuery
  649. ->whereIn('client_id', $this->getMyClientIds());
  650. }
  651. if ($_onlyUnstamped) {
  652. $measurementsQuery
  653. ->whereNotNull('client_bdt_measurement_id')
  654. ->whereNotNull('ts')
  655. ->where('is_cellular_zero', false)
  656. ->where(function ($q) {
  657. $q->whereNull('status')
  658. ->orWhere(function ($q2) {
  659. $q2->where('status', '<>', 'ACK')
  660. ->where('status', '<>', 'INVALID_ACK');
  661. });
  662. });
  663. }
  664. $x = [];
  665. $measurements = $measurementsQuery->orderBy('ts', 'desc')->paginate(50);
  666. // eager load stuff needed in JS
  667. foreach ($measurements as $measurement) {
  668. // if ($measurement->client_bdt_measurement_id) {
  669. // $measurement->bdtMeasurement = $measurement->clientBDTMeasurement->measurement;
  670. // }
  671. unset($measurement->clientBDTMeasurement); // we do not need this travelling to the frontend
  672. $client = [
  673. "uid" => $measurement->client->uid,
  674. "name" => $measurement->client->displayName(),
  675. ];
  676. $measurement->patient = $client;
  677. $measurement->careMonth = $measurement->client->currentCareMonth();
  678. $measurement->timestamp = friendly_date_time($measurement->created_at);
  679. unset($measurement->client); // we do not need this travelling to the frontend
  680. // if($measurement->label == 'SBP' || $measurement->label = 'DBP'){
  681. // continue;
  682. // }
  683. $x[] = $measurement;
  684. }
  685. return $measurements;
  686. }
  687. public function companyPros()
  688. {
  689. return $this->hasMany(CompanyPro::class, 'pro_id', 'id')
  690. ->where('is_active', true);
  691. }
  692. public function companyProPayers()
  693. {
  694. return $this->hasMany(CompanyProPayer::class, 'pro_id', 'id');
  695. }
  696. public function isAssociatedWithMCPayer() {
  697. $companyProPayers = $this->companyProPayers;
  698. $foundMC = false;
  699. if($companyProPayers) {
  700. foreach ($companyProPayers as $companyProPayer) {
  701. if($companyProPayer->payer && $companyProPayer->payer->is_medicare) {
  702. $foundMC = true;
  703. break;
  704. }
  705. }
  706. }
  707. return $foundMC;
  708. }
  709. public function isAssociatedWithNonMCPayer($_payerID) {
  710. $companyProPayers = $this->companyProPayers;
  711. $foundNonMC = false;
  712. if($companyProPayers) {
  713. foreach ($companyProPayers as $companyProPayer) {
  714. if($companyProPayer->payer && !$companyProPayer->payer->is_medicare && $companyProPayer->payer->id === $_payerID) {
  715. $foundNonMC = true;
  716. break;
  717. }
  718. }
  719. }
  720. return $foundNonMC;
  721. }
  722. public function companyLocations() {
  723. $companyProPayers = $this->companyProPayers;
  724. $companyIDs = [];
  725. foreach ($companyProPayers as $companyProPayer) {
  726. $companyIDs[] = $companyProPayer->company_id;
  727. }
  728. $locations = [];
  729. if(count($companyIDs)) {
  730. $locations = CompanyLocation::whereIn('id', $companyIDs)->get();
  731. }
  732. return $locations;
  733. }
  734. public function shadowClient() {
  735. return $this->hasOne(Client::class, 'id', 'shadow_client_id');
  736. }
  737. public function defaultCompanyPro() {
  738. return $this->hasOne(CompanyPro::class, 'id', 'default_company_pro_id');
  739. }
  740. public function currentNotePickupForProcessing() {
  741. return $this->hasOne(NotePickupForProcessing::class, 'id', 'current_note_pickup_for_processing_id');
  742. }
  743. public function get_patients_not_seen_in_45_days_count_as_mcp(){
  744. return 0;
  745. }
  746. }