Pro.php 28 KB

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