Pro.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811
  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. return $this->is_considered_for_dna;
  48. }
  49. public function lastPayment() {
  50. return ProTransaction
  51. ::where('pro_id', $this->id)
  52. ->where('plus_or_minus', 'PLUS')
  53. ->orderBy('created_at', 'desc')
  54. ->first();
  55. }
  56. public function hasRates() {
  57. $numRates = ProRate::where('is_active', true)->where('pro_id', $this->id)->count();
  58. return $numRates > 0;
  59. }
  60. public function cmRates() {
  61. return ProRate::distinct('code')
  62. ->where('is_active', true)
  63. ->where('pro_id', $this->id)
  64. ->where('code', 'LIKE', 'CM%')
  65. ->get();
  66. }
  67. public function rmRates() {
  68. return ProRate::distinct('code')
  69. ->where('is_active', true)
  70. ->where('pro_id', $this->id)
  71. ->where('code', 'LIKE', 'RM%')
  72. ->get();
  73. }
  74. public function noteRates() {
  75. return ProRate::distinct('code')
  76. ->where('is_active', true)
  77. ->where('pro_id', $this->id)
  78. ->where('code', 'NOT LIKE', 'CM%')
  79. ->where('code', 'NOT LIKE', 'RM%')
  80. ->where('responsibility', '<>', 'GENERIC')
  81. ->get();
  82. }
  83. public function genericRates() {
  84. return ProRate::distinct('code')
  85. ->where('is_active', true)
  86. ->where('pro_id', $this->id)
  87. ->where('responsibility', 'GENERIC')
  88. ->get();
  89. }
  90. public function recentDebits() {
  91. return ProTransaction
  92. ::where('pro_id', $this->id)
  93. ->where('plus_or_minus', 'PLUS')
  94. ->orderBy('created_at', 'desc')
  95. ->skip(0)->take(4)->get();
  96. }
  97. public function shortcuts() {
  98. return $this->hasMany(ProTextShortcut::class, 'pro_id')->where('is_removed', false);
  99. }
  100. public function allShortcuts() {
  101. $myId = $this->id;
  102. $shortcuts = ProTextShortcut::where('is_removed', false)
  103. ->where(function ($query2) use ($myId) {
  104. $query2
  105. ->where('pro_id', $myId)
  106. ->orWhereNull('pro_id');
  107. })
  108. ->get();
  109. return $shortcuts;
  110. }
  111. public function noteTemplates() {
  112. return $this->hasMany(NoteTemplatePro::class, 'pro_id')
  113. ->where('is_removed', false)
  114. ->orderBy('position_index', 'asc');
  115. }
  116. public function visitTemplates() {
  117. //TODO: use visit access
  118. return VisitTemplate::all();
  119. }
  120. public function currentWork() {
  121. return ProClientWork::where('pro_id', $this->id)->where('is_active', true)->first();
  122. }
  123. public function isWorkingOnClient($_client) {
  124. $count = ProClientWork::where('pro_id', $this->id)->where('client_id', $_client->id)->where('is_active', true)->count();
  125. return $count > 0;
  126. }
  127. public function canvasCustomItems($_key) {
  128. return ClientCanvasDataCustomItem::where('key', $_key)->get();
  129. }
  130. /**
  131. * @param $_start - YYYY-MM-DD
  132. * @param $_end - YYYY-MM-DD
  133. * @param string $_timezone - defaults to EASTERN
  134. * @param string $_availableBG - defaults to #00a
  135. * @param string $_unavailableBG - defaults to #a00
  136. * @return array
  137. * @throws Exception
  138. */
  139. public function getAvailabilityEvents($_start, $_end, $_timezone = 'EASTERN', $_availableBG = '#00a', $_unavailableBG = '#a00') {
  140. $_start .= ' 00:00:00';
  141. $_end .= ' 23:59:59';
  142. // get availability data
  143. $proGenAvail = ProGeneralAvailability
  144. ::where('is_cancelled', false)
  145. ->where('pro_id', $this->id)
  146. ->get();
  147. $proSpecAvail = ProSpecificAvailability
  148. ::where('is_cancelled', false)
  149. ->where('pro_id', $this->id)
  150. ->where(function ($query) use ($_start, $_end) {
  151. $query
  152. ->where(function ($query2) use ($_start, $_end) {
  153. $query2
  154. ->where('start_time', '>=', $_start)
  155. ->where('start_time', '<=', $_end);
  156. })
  157. ->orWhere(function ($query2) use ($_start, $_end) {
  158. $query2
  159. ->where('end_time', '>=', $_start)
  160. ->where('end_time', '<=', $_end);
  161. });
  162. })
  163. ->get();
  164. $proSpecUnavail = ProSpecificUnavailability
  165. ::where('is_cancelled', false)
  166. ->where('pro_id', $this->id)
  167. ->where(function ($query) use ($_start, $_end) {
  168. $query
  169. ->where(function ($query2) use ($_start, $_end) {
  170. $query2
  171. ->where('start_time', '>=', $_start)
  172. ->where('start_time', '<=', $_end);
  173. })
  174. ->orWhere(function ($query2) use ($_start, $_end) {
  175. $query2
  176. ->where('end_time', '>=', $_start)
  177. ->where('end_time', '<=', $_end);
  178. });
  179. })
  180. ->get();
  181. // default GA
  182. // if no gen avail, assume mon to fri, 9 to 7
  183. /*if (count($proGenAvail) === 0) {
  184. $dayNames = ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY'];
  185. foreach ($dayNames as $dayName) {
  186. $item = new \stdClass();
  187. $item->day_of_week = $dayName;
  188. $item->timezone = $_timezone;
  189. $item->start_time = '09:00:00';
  190. $item->end_time = '18:00:00';
  191. $proGenAvail->push($item);
  192. }
  193. }*/
  194. // create timeline
  195. $phpTZ = appTZtoPHPTZ($_timezone);
  196. $phpTZObject = new \DateTimeZone($phpTZ);
  197. $startDate = new \DateTime($_start, $phpTZObject);
  198. $endDate = new \DateTime($_end, $phpTZObject);
  199. $proTimeLine = new TimeLine($startDate, $endDate);
  200. // General availability
  201. $period = new \DatePeriod($startDate, \DateInterval::createFromDateString('1 day'), $endDate);
  202. $days = [];
  203. foreach ($period as $day) {
  204. $days[] = [
  205. "day" => strtoupper($day->format("l")), // SUNDAY, etc.
  206. "date" => $day->format("Y-m-d"), // 2020-10-04, etc.
  207. ];
  208. }
  209. foreach ($days as $day) {
  210. $proGenAvailForTheDay = $proGenAvail->filter(function ($record) use ($day) {
  211. return $record->day_of_week === $day["day"];
  212. });
  213. foreach ($proGenAvailForTheDay as $ga) {
  214. $gaStart = new \DateTime($day["date"], new \DateTimeZone(appTZtoPHPTZ($ga->timezone)));
  215. $parts = explode(":", $ga->start_time);
  216. $gaStart->setTime(intval($parts[0]), intval($parts[1]), intval($parts[2]));
  217. $gaStart->setTimezone($phpTZObject);
  218. $gaEnd = new \DateTime($day["date"], new \DateTimeZone(appTZtoPHPTZ($ga->timezone)));
  219. $parts = explode(":", $ga->end_time);
  220. $gaEnd->setTime(intval($parts[0]), intval($parts[1]), intval($parts[2]));
  221. $gaEnd->setTimezone($phpTZObject);
  222. $proTimeLine->addAvailability($gaStart, $gaEnd);
  223. }
  224. }
  225. // specific availability
  226. foreach ($proSpecAvail as $sa) {
  227. $saStart = new \DateTime($sa->start_time, new \DateTimeZone(appTZtoPHPTZ($sa->timezone)));
  228. $saStart->setTimezone($phpTZObject);
  229. $saEnd = new \DateTime($sa->end_time, new \DateTimeZone(appTZtoPHPTZ($sa->timezone)));
  230. $saEnd->setTimezone($phpTZObject);
  231. $proTimeLine->addAvailability($saStart, $saEnd);
  232. }
  233. // specific unavailability
  234. foreach ($proSpecUnavail as $sua) {
  235. $suaStart = new \DateTime($sua->start_time, new \DateTimeZone(appTZtoPHPTZ($sua->timezone)));
  236. $suaStart->setTimezone($phpTZObject);
  237. $suaEnd = new \DateTime($sua->end_time, new \DateTimeZone(appTZtoPHPTZ($sua->timezone)));
  238. $suaEnd->setTimezone($phpTZObject);
  239. $proTimeLine->removeAvailability($suaStart, $suaEnd);
  240. }
  241. $events = [];
  242. // availability
  243. foreach ($proTimeLine->getAvailable() as $item) {
  244. $eStart = new \DateTime('@' . $item->start);
  245. $eStart->setTimezone($phpTZObject);
  246. $eEnd = new \DateTime('@' . $item->end);
  247. $eEnd->setTimezone($phpTZObject);
  248. $events[] = [
  249. "type" => "availability",
  250. "start" => $eStart->format('Y-m-d H:i:s'),
  251. "end" => $eEnd->format('Y-m-d H:i:s'),
  252. "editable" => false,
  253. "backgroundColor" => $_availableBG
  254. ];
  255. }
  256. // unavailability
  257. foreach ($proTimeLine->getUnavailable() as $item) {
  258. $eStart = new \DateTime('@' . $item->start);
  259. $eStart->setTimezone($phpTZObject);
  260. $eEnd = new \DateTime('@' . $item->end);
  261. $eEnd->setTimezone($phpTZObject);
  262. $events[] = [
  263. "type" => "unavailability",
  264. "start" => $eStart->format('Y-m-d H:i:s'),
  265. "end" => $eEnd->format('Y-m-d H:i:s'),
  266. "editable" => false,
  267. "backgroundColor" => $_unavailableBG
  268. ];
  269. }
  270. return $events;
  271. }
  272. public function getMyClientIds($_search = false) {
  273. $clients = $this->getAccessibleClientsQuery($_search)->get();
  274. $clientIds = [];
  275. foreach($clients as $client){
  276. $clientIds[] = $client->id;
  277. }
  278. return $clientIds;
  279. }
  280. public function favoritesByCategory($_category) {
  281. return ProFavorite::where('pro_id', $this->id)
  282. ->where('is_removed', false)
  283. ->where('category', $_category)
  284. ->orderBy('category', 'asc')
  285. ->orderBy('position_index', 'asc')
  286. ->get();
  287. }
  288. function get_patients_count_as_mcp() {
  289. $query = Client::whereNull('shadow_pro_id');
  290. return $query->where('mcp_pro_id', $this->id)->count();
  291. }
  292. function get_new_patients_awaiting_visit_count_as_mcp() {
  293. $query = Client::whereNull('shadow_pro_id');
  294. return $query->where('mcp_pro_id', $this->id)
  295. ->where('has_mcp_done_onboarding_visit', '!=', 'YES')
  296. ->count();
  297. }
  298. function get_notes_pending_signature_count_as_mcp() {
  299. return Note::where('hcp_pro_id', $this->id)
  300. ->where('is_cancelled', '<>', true)
  301. ->where('is_core_note', '<>', true)
  302. ->where('is_signed_by_hcp', '<>', true)
  303. ->count();
  304. }
  305. function get_notes_pending_signature_count_as_dna() {
  306. return;
  307. $naBillableSignedNotes = DB::select(DB::raw("
  308. SELECT count(note.id) as na_billable_notes
  309. FROM note
  310. WHERE
  311. note.is_signed_by_hcp = TRUE AND
  312. note.ally_pro_id = :pro_id AND
  313. note.is_cancelled = FALSE AND
  314. (
  315. SELECT count(bill.id)
  316. FROM bill
  317. WHERE
  318. bill.is_cancelled = FALSE AND
  319. bill.generic_pro_id = :pro_id AND
  320. bill.note_id = note.id
  321. ) = 0
  322. "), ["pro_id" => $performerProID]);
  323. if(!$naBillableSignedNotes || !count($naBillableSignedNotes)) {
  324. $naBillableSignedNotes = 0;
  325. }
  326. else {
  327. $naBillableSignedNotes = $naBillableSignedNotes[0]->na_billable_notes;
  328. }
  329. }
  330. function get_notes_pending_billing_count_as_mcp() {
  331. return Note::where('hcp_pro_id', $this->id)
  332. ->where('is_cancelled', '<>', true)
  333. ->where('is_signed_by_hcp', true)
  334. ->where('is_billing_marked_done', '<>', true)
  335. ->count();
  336. }
  337. function get_bills_pending_signature_count_as_mcp(){
  338. return;
  339. $pendingBillsToSign = Bill::where('bill_service_type', '<>', 'CARE_MONTH')->where(function ($query) use ($performerProID) {
  340. $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_cancelled', false);
  341. })
  342. ->orWhere(function ($query) use ($performerProID) {
  343. $query->where('cm_pro_id', $performerProID)->where('is_signed_by_cm', false)->where('is_cancelled', false);;
  344. })->orWhere(function ($query) use ($performerProID) {
  345. $query->where('rme_pro_id', $performerProID)->where('is_signed_by_rme', false)->where('is_cancelled', false);;
  346. })->orWhere(function ($query) use ($performerProID) {
  347. $query->where('rmm_pro_id', $performerProID)->where('is_signed_by_rmm', false)->where('is_cancelled', false);;
  348. })->count();
  349. $keyNumbers['pendingBillsToSign'] = $pendingBillsToSign;
  350. }
  351. function get_measurements_awaiting_review_count_as_mcp() {
  352. $result = DB::select(DB::raw("
  353. SELECT SUM(rm_num_measurements_not_stamped_by_mcp) AS count
  354. FROM care_month
  355. WHERE mcp_pro_id = :pro_id
  356. AND rm_num_measurements_not_stamped_by_mcp IS NOT NULL
  357. AND rm_num_measurements_not_stamped_by_mcp > 0;
  358. "), ["pro_id" => $this->id]);
  359. if($result) return $result[0]->count;
  360. }
  361. function get_incoming_reports_pending_signature_count_as_mcp() {
  362. return IncomingReport::where('hcp_pro_id', $this->id)
  363. ->where('has_hcp_pro_signed', '<>', true)
  364. ->where('is_entry_error', '<>', true)
  365. ->count();
  366. }
  367. function get_patients_without_appointment_query() {
  368. return Client::where('mcp_pro_id', $this->id)
  369. ->where(function($q){
  370. $q->whereNull('next_mcp_appointment_id')
  371. ->orWhere('next_mcp_appointment_date', '<=', DB::raw('NOW()::DATE'));
  372. });
  373. }
  374. function get_patients_without_appointment_count_as_mcp() {
  375. return $this->get_patients_without_appointment_query()->count();
  376. }
  377. function get_patients_overdue_for_visit_query() {
  378. return Client::where('mcp_pro_id', $this->id)
  379. ->where(function($q){
  380. $q->whereNull('most_recent_completed_mcp_note_id')
  381. ->orWhere('most_recent_completed_mcp_note_date', '<', DB::raw("NOW()::DATE - INTERVAL '45 DAY'"));
  382. });
  383. }
  384. function get_patients_overdue_count_as_mcp() {
  385. return $this->get_patients_overdue_for_visit_query()->count();
  386. }
  387. function get_patients_without_remote_measurement_in_48_hours_count_as_mcp() {
  388. }
  389. function get_cancelled_appointments_pending_acknowledgement_count_as_mcp_query() {
  390. // SELECT * FROM appointment WHERE hcp_pro_id = :me.id AND status = 'REJECTED' AND wasAcknowledgedByAppointmentPro IS NOT TRUE;
  391. return Appointment::where('pro_id', $this->id)
  392. ->where('latest_confirmation_decision_enum', 'REJECTED')
  393. ->where('is_decision_acknowledgement_from_appointment_pro_pending', true);
  394. }
  395. function get_cancelled_appointments_pending_acknowledgement_count_as_mcp() {
  396. // SELECT * FROM appointment WHERE hcp_pro_id = :me.id AND status = 'REJECTED' AND wasAcknowledgedByAppointmentPro IS NOT TRUE;
  397. return $this->get_cancelled_appointments_pending_acknowledgement_count_as_mcp_query()->count();
  398. }
  399. function get_cancelled_bills_awaiting_review_count_as_mcp() {
  400. // SELECT * FROM bill WHERE bill_service_type = 'NOTE' AND is_cancelled IS TRUE AND isCancellationAcknowledged IS FALSE;
  401. return Bill::where('hcp_pro_id', $this->id)
  402. ->where('bill_service_type', 'NOTE')
  403. ->where('is_cancelled', true)
  404. ->where('is_cancellation_acknowledged', '<>', true)
  405. ->count();
  406. }
  407. function get_cancelled_supply_orders_awaiting_review_count_as_mcp() {
  408. // SELECT * FROM supply_order WHERE signed_by_pro_id = :me.id AND is_cancelled IS TRUE AND isCancellationAcknowledged IS NOT TRUE;
  409. return SupplyOrder::where('signed_by_pro_id', $this->id)
  410. ->where('is_cancelled', true)
  411. ->where('is_cancellation_acknowledged', '<>', true)
  412. ->count();
  413. }
  414. function get_erx_and_orders_awaiting_signature_count_as_mcp() {
  415. // SELECT * FROM erx WHERE hcp_pro_id = :me.id AND pro_declared_status <> 'CANCELLED' AND hasHcpProSigned IS NOT TRUE;
  416. return Erx::where('hcp_pro_id', $this->id)
  417. ->where('pro_declared_status', '<>', 'CANCELLED')
  418. ->where('has_hcp_pro_signed', '<>', true)
  419. ->count();
  420. }
  421. function get_supply_orders_awaiting_signature_count_as_mcp() {
  422. // 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;
  423. return SupplyOrder::where('created_by_pro_id', $this->id)
  424. ->whereNull('signed_by_pro_id')
  425. ->where('is_cancelled', '<>', true)
  426. ->count();
  427. }
  428. function get_birthdays_today_as_mcp(){
  429. return;
  430. $queryClients = $this->performer()->pro->getAccessibleClientsQuery();
  431. $keyNumbers['patientsHavingBirthdayToday'] = $queryClients
  432. ->whereRaw('EXTRACT(DAY from dob) = ?', [date('d')])
  433. ->whereRaw('EXTRACT(MONTH from dob) = ?', [date('m')])
  434. ->count();
  435. $reimbursement = [];
  436. $reimbursement["currentBalance"] = $performer->pro->balance;
  437. $reimbursement["nextPaymentDate"] = '--';
  438. $lastPayment = ProTransaction::where('pro_id', $performerProID)->where('plus_or_minus', 'PLUS')->orderBy('created_at', 'DESC')->first();
  439. if ($lastPayment) {
  440. $reimbursement["lastPayment"] = $lastPayment->amount;
  441. $reimbursement["lastPaymentDate"] = $lastPayment->created_at;
  442. } else {
  443. $reimbursement["lastPayment"] = '--';
  444. $reimbursement["lastPaymentDate"] = '--';
  445. }
  446. }
  447. public function getAppointmentsPendingStatusChangeAck() {
  448. return Appointment::where('pro_id', $this->id)
  449. ->where('is_status_acknowledgement_from_appointment_pro_pending', true)
  450. ->where('raw_date', '>=', DB::raw('NOW()'))
  451. ->orderBy('raw_date', 'asc')
  452. ->get();
  453. }
  454. public function getAppointmentsPendingDecisionAck() {
  455. return Appointment::where('pro_id', $this->id)
  456. ->where('is_decision_acknowledgement_from_appointment_pro_pending', true)
  457. ->where('raw_date', '>=', DB::raw('NOW()'))
  458. ->orderBy('raw_date', 'asc')
  459. ->get();
  460. }
  461. public function getAppointmentsPendingTimeChangeAck() {
  462. return Appointment::where('pro_id', $this->id)
  463. ->where('is_time_change_acknowledgement_from_appointment_pro_pending', true)
  464. ->where('raw_date', '>=', DB::raw('NOW()'))
  465. ->orderBy('raw_date', 'asc')
  466. ->get();
  467. }
  468. public function getAccessibleClientsQuery($_search = false) {
  469. $proID = $this->id;
  470. $query = Client::whereNull('shadow_pro_id');
  471. if ($this->pro_type === 'ADMIN' && ($_search ? $this->can_see_any_client_via_search : $this->can_see_all_clients_in_list)) {
  472. $query = $query->where('id', '>', 0);
  473. } else {
  474. $query = $query->where(function ($q) use ($proID) {
  475. $q->where('mcp_pro_id', $proID)
  476. ->orWhere('cm_pro_id', $proID)
  477. ->orWhere('rmm_pro_id', $proID)
  478. ->orWhere('rme_pro_id', $proID)
  479. ->orWhere('physician_pro_id', $proID)
  480. ->orWhere('default_na_pro_id', $proID)
  481. ->orWhereRaw('id IN (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = ?)', [$proID])
  482. ->orWhereRaw('id IN (SELECT client_id FROM appointment WHERE status NOT IN (\'CANCELLED\') AND pro_id = ?)', [$proID])
  483. ->orWhereRaw('id IN (SELECT mcp_pro_id FROM client_program WHERE client_id = client.id AND is_active = TRUE)')
  484. ->orWhereRaw('id IN (SELECT manager_pro_id FROM client_program WHERE client_id = client.id AND is_active = TRUE)')
  485. ->orWhereRaw('id IN (SELECT client_id FROM note WHERE ally_pro_id = ? AND is_cancelled = FALSE)', [$proID]);;
  486. });
  487. }
  488. return $query;
  489. }
  490. public function canAccess($_patientUid) {
  491. $proID = $this->id;
  492. if ($this->pro_type === 'ADMIN') {
  493. return true;
  494. }
  495. $canAccess = Client::select('uid')
  496. ->where('uid', $_patientUid)
  497. ->where(function ($q) use ($proID) {
  498. $q->where('mcp_pro_id', $proID)
  499. ->orWhere('cm_pro_id', $proID)
  500. ->orWhere('rmm_pro_id', $proID)
  501. ->orWhere('rme_pro_id', $proID)
  502. ->orWhere('physician_pro_id', $proID)
  503. ->orWhere('default_na_pro_id', $proID)
  504. ->orWhereRaw('id IN (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = ?)', [$proID])
  505. ->orWhereRaw('id IN (SELECT client_id FROM appointment WHERE status NOT IN (\'CANCELLED\') AND pro_id = ?)', [$proID])
  506. ->orWhereRaw('id IN (SELECT mcp_pro_id FROM client_program WHERE client_id = client.id AND is_active = TRUE)')
  507. ->orWhereRaw('id IN (SELECT manager_pro_id FROM client_program WHERE client_id = client.id AND is_active = TRUE)')
  508. ->orWhereRaw('id IN (SELECT client_id FROM note WHERE ally_pro_id = ? AND is_cancelled = FALSE)', [$proID]);
  509. })->count();
  510. return !!$canAccess;
  511. }
  512. public function canAddCPMEntryForMeasurement(Measurement $measurement, Pro $pro)
  513. {
  514. // check if client has any programs where this measurement type is allowed
  515. $allowed = false;
  516. $client = $measurement->client;
  517. $clientPrograms = $client->clientPrograms;
  518. if($pro->pro_type !== 'ADMIN') {
  519. $clientPrograms = $clientPrograms->filter(function($_clientProgram) use ($pro) {
  520. return $_clientProgram->manager_pro_id === $pro->id;
  521. });
  522. }
  523. if(count($clientPrograms)) {
  524. foreach ($clientPrograms as $clientProgram) {
  525. if(strpos(strtolower($clientProgram->measurement_labels), '|' . strtolower($measurement->label) . '|') !== FALSE) {
  526. $allowed = true;
  527. break;
  528. }
  529. }
  530. }
  531. return $allowed ? $clientPrograms : FALSE;
  532. }
  533. public function getUnstampedMeasurementsFromCurrentMonth($_countOnly, $skip, $limit)
  534. {
  535. date_default_timezone_set('US/Eastern');
  536. $start = strtotime(date('Y-m-01'));
  537. $end = date_add(date_create(date('Y-m-01')), date_interval_create_from_date_string("1 month"))->getTimestamp();
  538. $start *= 1000;
  539. $end *= 1000;
  540. $measurementsQuery = Measurement::where('is_removed', false)
  541. ->join('client', 'client.id', '=', 'measurement.client_id')
  542. ->whereNotNull('measurement.client_bdt_measurement_id')
  543. ->whereNotNull('measurement.ts')
  544. ->where('measurement.is_cellular_zero', false)
  545. ->where('measurement.ts', '>=', $start)
  546. ->where('measurement.ts', '<', $end)
  547. ->whereIn('measurement.client_id', $this->getMyClientIds())
  548. ->where(function ($q) {
  549. $q
  550. ->where(function ($q2) {
  551. $q2
  552. ->where('client.mcp_pro_id', $this->id)
  553. ->where('measurement.has_been_stamped_by_mcp', false);
  554. })
  555. ->orWhere(function ($q2) {
  556. $q2
  557. ->where('client.default_na_pro_id', $this->id)
  558. ->where('measurement.has_been_stamped_by_non_hcp', false);
  559. })
  560. ->orWhere(function ($q2) {
  561. $q2
  562. ->where('client.rmm_pro_id', $this->id)
  563. ->where('measurement.has_been_stamped_by_rmm', false);
  564. })
  565. ->orWhere(function ($q2) {
  566. $q2
  567. ->where('client.rme_pro_id', $this->id)
  568. ->where('measurement.has_been_stamped_by_rme', false);
  569. });
  570. });
  571. if($_countOnly) {
  572. return $measurementsQuery->count();
  573. }
  574. $x = [];
  575. $measurements = $measurementsQuery
  576. ->orderBy('ts', 'desc')
  577. ->skip($skip)
  578. ->take($limit)
  579. ->get();
  580. // eager load stuff needed in JS
  581. foreach ($measurements as $measurement) {
  582. // if ($measurement->client_bdt_measurement_id) {
  583. // $measurement->bdtMeasurement = $measurement->clientBDTMeasurement->measurement;
  584. // }
  585. unset($measurement->clientBDTMeasurement); // we do not need this travelling to the frontend
  586. $client = [
  587. "uid" => $measurement->client->uid,
  588. "name" => $measurement->client->displayName(),
  589. ];
  590. $measurement->patient = $client;
  591. $measurement->careMonth = $measurement->client->currentCareMonth();
  592. $measurement->timestamp = friendlier_date_time($measurement->created_at);
  593. unset($measurement->client); // we do not need this travelling to the frontend
  594. if(@$measurement->detail_json) unset($measurement->detail_json);
  595. if(@$measurement->canvas_data) unset($measurement->canvas_data);
  596. if(@$measurement->latest_measurements) unset($measurement->latest_measurements);
  597. if(@$measurement->info_lines) unset($measurement->info_lines);
  598. if(@$measurement->canvas_data_backup) unset($measurement->canvas_data_backup);
  599. if(@$measurement->migrated_canvas_data_backup) unset($measurement->migrated_canvas_data_backup);
  600. // if($measurement->label == 'SBP' || $measurement->label = 'DBP'){
  601. // continue;
  602. // }
  603. $x[] = $measurement;
  604. }
  605. // dd($measurements);
  606. return $measurements;
  607. }
  608. public function getMeasurements($_onlyUnstamped = true)
  609. {
  610. $measurementsQuery = Measurement::where('is_removed', false);
  611. if ($this->pro_type != 'ADMIN') {
  612. $measurementsQuery
  613. ->whereIn('client_id', $this->getMyClientIds());
  614. }
  615. if ($_onlyUnstamped) {
  616. $measurementsQuery
  617. ->whereNotNull('client_bdt_measurement_id')
  618. ->whereNotNull('ts')
  619. ->where('is_cellular_zero', false)
  620. ->where(function ($q) {
  621. $q->whereNull('status')
  622. ->orWhere(function ($q2) {
  623. $q2->where('status', '<>', 'ACK')
  624. ->where('status', '<>', 'INVALID_ACK');
  625. });
  626. });
  627. }
  628. $x = [];
  629. $measurements = $measurementsQuery->orderBy('ts', 'desc')->paginate(50);
  630. // eager load stuff needed in JS
  631. foreach ($measurements as $measurement) {
  632. // if ($measurement->client_bdt_measurement_id) {
  633. // $measurement->bdtMeasurement = $measurement->clientBDTMeasurement->measurement;
  634. // }
  635. unset($measurement->clientBDTMeasurement); // we do not need this travelling to the frontend
  636. $client = [
  637. "uid" => $measurement->client->uid,
  638. "name" => $measurement->client->displayName(),
  639. ];
  640. $measurement->patient = $client;
  641. $measurement->careMonth = $measurement->client->currentCareMonth();
  642. $measurement->timestamp = friendly_date_time($measurement->created_at);
  643. unset($measurement->client); // we do not need this travelling to the frontend
  644. // if($measurement->label == 'SBP' || $measurement->label = 'DBP'){
  645. // continue;
  646. // }
  647. $x[] = $measurement;
  648. }
  649. return $measurements;
  650. }
  651. public function companyPros()
  652. {
  653. return $this->hasMany(CompanyPro::class, 'pro_id', 'id')
  654. ->where('is_active', true);
  655. }
  656. public function companyProPayers()
  657. {
  658. return $this->hasMany(CompanyProPayer::class, 'pro_id', 'id');
  659. }
  660. public function isAssociatedWithMCPayer() {
  661. $companyProPayers = $this->companyProPayers;
  662. $foundMC = false;
  663. if($companyProPayers) {
  664. foreach ($companyProPayers as $companyProPayer) {
  665. if($companyProPayer->payer && $companyProPayer->payer->is_medicare) {
  666. $foundMC = true;
  667. break;
  668. }
  669. }
  670. }
  671. return $foundMC;
  672. }
  673. public function isAssociatedWithNonMCPayer($_payerID) {
  674. $companyProPayers = $this->companyProPayers;
  675. $foundNonMC = false;
  676. if($companyProPayers) {
  677. foreach ($companyProPayers as $companyProPayer) {
  678. if($companyProPayer->payer && !$companyProPayer->payer->is_medicare && $companyProPayer->payer->id === $_payerID) {
  679. $foundNonMC = true;
  680. break;
  681. }
  682. }
  683. }
  684. return $foundNonMC;
  685. }
  686. public function companyLocations() {
  687. $companyProPayers = $this->companyProPayers;
  688. $companyIDs = [];
  689. foreach ($companyProPayers as $companyProPayer) {
  690. $companyIDs[] = $companyProPayer->company_id;
  691. }
  692. $locations = [];
  693. if(count($companyIDs)) {
  694. $locations = CompanyLocation::whereIn('id', $companyIDs)->get();
  695. }
  696. return $locations;
  697. }
  698. public function shadowClient() {
  699. return $this->hasOne(Client::class, 'id', 'shadow_client_id');
  700. }
  701. public function defaultCompanyPro() {
  702. return $this->hasOne(CompanyPro::class, 'id', 'default_company_pro_id');
  703. }
  704. public function currentNotePickupForProcessing() {
  705. return $this->hasOne(NotePickupForProcessing::class, 'id', 'current_note_pickup_for_processing_id');
  706. }
  707. public function get_patients_not_seen_in_45_days_count_as_mcp(){
  708. return 0;
  709. }
  710. }