Pro.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  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)
  129. ->where('pro_id', $this->id)
  130. ->orderBy('label')
  131. ->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_patients_count_as_dna() {
  296. $query = Client::whereNull('shadow_pro_id');
  297. return $query->where('default_na_pro_id', $this->id)->count();
  298. }
  299. function get_new_patients_awaiting_visit_count_as_mcp() {
  300. $query = Client::whereNull('shadow_pro_id');
  301. return $query->where('mcp_pro_id', $this->id)
  302. ->where('has_mcp_done_onboarding_visit', '!=', 'YES')
  303. ->count();
  304. }
  305. function get_new_patients_awaiting_visit_count_as_dna() {
  306. $query = Client::whereNull('shadow_pro_id');
  307. return $query->where('default_na_pro_id', $this->id)
  308. ->where('has_mcp_done_onboarding_visit', '!=', 'YES')
  309. ->count();
  310. }
  311. function get_notes_pending_signature_count_as_mcp() {
  312. return Note::where('hcp_pro_id', $this->id)
  313. ->where('is_cancelled', '<>', true)
  314. ->where('is_core_note', '<>', true)
  315. ->where('is_signed_by_hcp', '<>', true)
  316. ->count();
  317. }
  318. function get_notes_pending_signature_count_as_dna() {
  319. return Note::where('ally_pro_id', $this->id)
  320. ->where('is_cancelled', '<>', true)
  321. ->where('is_core_note', '<>', true)
  322. ->where('is_signed_by_ally', '<>', true)
  323. ->count();
  324. }
  325. function get_notes_pending_billing_count_as_mcp() {
  326. return Note::where('hcp_pro_id', $this->id)
  327. ->where('is_cancelled', '<>', true)
  328. ->where('is_signed_by_hcp', true)
  329. ->where('is_billing_marked_done', '<>', true)
  330. ->count();
  331. }
  332. function get_notes_pending_billing_count_as_dna() {
  333. return Note::where('ally_pro_id', $this->id)
  334. ->where('is_cancelled', '<>', true)
  335. ->where('is_signed_by_hcp', true)
  336. ->where('is_billing_marked_done', '<>', true)
  337. ->count();
  338. }
  339. function get_measurements_awaiting_review_count_as_mcp() {
  340. $result = DB::select(DB::raw("
  341. SELECT SUM(rm_num_measurements_not_stamped_by_mcp) AS count
  342. FROM care_month
  343. WHERE mcp_pro_id = :pro_id
  344. AND rm_num_measurements_not_stamped_by_mcp IS NOT NULL
  345. AND rm_num_measurements_not_stamped_by_mcp > 0;
  346. "), ["pro_id" => $this->id]);
  347. if($result) return $result[0]->count;
  348. }
  349. function get_bills_pending_signature_count_as_mcp(){
  350. return;
  351. $pendingBillsToSign = Bill::where('bill_service_type', '<>', 'CARE_MONTH')->where(function ($query) use ($performerProID) {
  352. $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_cancelled', false);
  353. })
  354. ->orWhere(function ($query) use ($performerProID) {
  355. $query->where('cm_pro_id', $performerProID)->where('is_signed_by_cm', false)->where('is_cancelled', false);;
  356. })->orWhere(function ($query) use ($performerProID) {
  357. $query->where('rme_pro_id', $performerProID)->where('is_signed_by_rme', false)->where('is_cancelled', false);;
  358. })->orWhere(function ($query) use ($performerProID) {
  359. $query->where('rmm_pro_id', $performerProID)->where('is_signed_by_rmm', false)->where('is_cancelled', false);;
  360. })->count();
  361. $keyNumbers['pendingBillsToSign'] = $pendingBillsToSign;
  362. }
  363. function get_incoming_reports_pending_signature_count_as_mcp() {
  364. return IncomingReport::where('hcp_pro_id', $this->id)
  365. ->where('has_hcp_pro_signed', '<>', true)
  366. ->where('is_entry_error', '<>', true)
  367. ->count();
  368. }
  369. function get_patients_without_appointment_query() {
  370. return Client::where('mcp_pro_id', $this->id)
  371. ->whereNull('today_mcp_appointment_date')
  372. ->where(function($q){
  373. $q->whereNull('next_mcp_appointment_id')
  374. ->orWhere('next_mcp_appointment_date', '<=', DB::raw('NOW()::DATE'));
  375. });
  376. }
  377. function get_patients_without_appointment_for_dna_query() {
  378. return Client::where('default_na_pro_id', $this->id)
  379. ->whereNull('today_mcp_appointment_date')
  380. ->where(function($q){
  381. $q->whereNull('next_mcp_appointment_id')
  382. ->orWhere('next_mcp_appointment_date', '<=', DB::raw('NOW()::DATE'));
  383. });
  384. }
  385. function get_patients_without_appointment_count_as_mcp() {
  386. return $this->get_patients_without_appointment_query()->count();
  387. }
  388. function get_patients_without_appointment_count_as_dna() {
  389. return $this->get_patients_without_appointment_for_dna_query()->count();
  390. }
  391. function get_patients_overdue_for_visit_query() {
  392. return Client::where('mcp_pro_id', $this->id)
  393. ->where(function($q){
  394. $q->whereNull('most_recent_completed_mcp_note_id')
  395. ->orWhere('most_recent_completed_mcp_note_date', '<', DB::raw("NOW()::DATE - INTERVAL '45 DAY'"));
  396. });
  397. }
  398. function get_patients_overdue_for_visit_for_dna_query() {
  399. return Client::where('default_na_pro_id', $this->id)
  400. ->where(function($q){
  401. $q->whereNull('most_recent_completed_mcp_note_id')
  402. ->orWhere('most_recent_completed_mcp_note_date', '<', DB::raw("NOW()::DATE - INTERVAL '45 DAY'"));
  403. });
  404. }
  405. function get_patients_overdue_count_as_mcp() {
  406. return $this->get_patients_overdue_for_visit_query()->count();
  407. }
  408. function get_patients_overdue_count_as_dna() {
  409. return $this->get_patients_overdue_for_visit_for_dna_query()->count();
  410. }
  411. function get_patients_without_remote_measurement_in_48_hours_count_as_mcp() {
  412. }
  413. function get_patients_without_remote_measurement_in_48_hours_count_as_dna() {
  414. }
  415. function get_cancelled_appointments_pending_acknowledgement_count_as_mcp_query() {
  416. // SELECT * FROM appointment WHERE hcp_pro_id = :me.id AND status = 'REJECTED' AND wasAcknowledgedByAppointmentPro IS NOT TRUE;
  417. return Appointment::where('pro_id', $this->id)
  418. ->where('latest_confirmation_decision_enum', 'REJECTED')
  419. ->where('is_decision_acknowledgement_from_appointment_pro_pending', true);
  420. }
  421. function get_cancelled_appointments_pending_acknowledgement_count_as_mcp() {
  422. // SELECT * FROM appointment WHERE hcp_pro_id = :me.id AND status = 'REJECTED' AND wasAcknowledgedByAppointmentPro IS NOT TRUE;
  423. return $this->get_cancelled_appointments_pending_acknowledgement_count_as_mcp_query()->count();
  424. }
  425. function get_cancelled_bills_awaiting_review_count_as_mcp() {
  426. // SELECT * FROM bill WHERE bill_service_type = 'NOTE' AND is_cancelled IS TRUE AND isCancellationAcknowledged IS FALSE;
  427. return Bill::where('hcp_pro_id', $this->id)
  428. ->where('bill_service_type', 'NOTE')
  429. ->where('is_cancelled', true)
  430. ->where('is_cancellation_acknowledged', '<>', true)
  431. ->count();
  432. }
  433. function get_cancelled_bills_awaiting_review_count_as_dna() {
  434. // SELECT * FROM bill WHERE bill_service_type = 'NOTE' AND is_cancelled IS TRUE AND isCancellationAcknowledged IS FALSE;
  435. return Bill::where('na_pro_id', $this->id)
  436. ->where('bill_service_type', 'NOTE')
  437. ->where('is_cancelled', true)
  438. ->where('is_cancellation_acknowledged', '<>', true)
  439. ->count();
  440. }
  441. function get_cancelled_supply_orders_awaiting_review_count_as_mcp() {
  442. // SELECT * FROM supply_order WHERE signed_by_pro_id = :me.id AND is_cancelled IS TRUE AND isCancellationAcknowledged IS NOT TRUE;
  443. return SupplyOrder::where('signed_by_pro_id', $this->id)
  444. ->where('is_cancelled', true)
  445. ->where('is_cancellation_acknowledged', '<>', true)
  446. ->count();
  447. }
  448. function get_erx_and_orders_awaiting_signature_count_as_mcp() {
  449. // SELECT * FROM erx WHERE hcp_pro_id = :me.id AND pro_declared_status <> 'CANCELLED' AND hasHcpProSigned IS NOT TRUE;
  450. return Erx::where('hcp_pro_id', $this->id)
  451. ->where('pro_declared_status', '<>', 'CANCELLED')
  452. ->where('has_hcp_pro_signed', '<>', true)
  453. ->count();
  454. }
  455. function get_supply_orders_awaiting_signature_count_as_mcp() {
  456. // 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;
  457. return SupplyOrder::where('created_by_pro_id', $this->id)
  458. ->whereNull('signed_by_pro_id')
  459. ->where('is_cancelled', '<>', true)
  460. ->count();
  461. }
  462. function get_supply_orders_awaiting_shipment_count_as_mcp() {
  463. return SupplyOrder::where('created_by_pro_id', $this->id)
  464. ->where('is_signed_by_pro', true)
  465. ->where('is_cleared_for_shipment', true)
  466. ->whereNull('shipment_id')
  467. ->count();
  468. }
  469. function get_birthdays_today_as_mcp(){
  470. return;
  471. $queryClients = $this->performer()->pro->getAccessibleClientsQuery();
  472. $keyNumbers['patientsHavingBirthdayToday'] = $queryClients
  473. ->whereRaw('EXTRACT(DAY from dob) = ?', [date('d')])
  474. ->whereRaw('EXTRACT(MONTH from dob) = ?', [date('m')])
  475. ->count();
  476. $reimbursement = [];
  477. $reimbursement["currentBalance"] = $performer->pro->balance;
  478. $reimbursement["nextPaymentDate"] = '--';
  479. $lastPayment = ProTransaction::where('pro_id', $performerProID)->where('plus_or_minus', 'PLUS')->orderBy('created_at', 'DESC')->first();
  480. if ($lastPayment) {
  481. $reimbursement["lastPayment"] = $lastPayment->amount;
  482. $reimbursement["lastPaymentDate"] = $lastPayment->created_at;
  483. } else {
  484. $reimbursement["lastPayment"] = '--';
  485. $reimbursement["lastPaymentDate"] = '--';
  486. }
  487. }
  488. public function getAppointmentsPendingStatusChangeAck() {
  489. return Appointment::where('pro_id', $this->id)
  490. ->where('is_status_acknowledgement_from_appointment_pro_pending', true)
  491. ->where('raw_date', '>=', DB::raw('NOW()'))
  492. ->orderBy('raw_date', 'asc')
  493. ->get();
  494. }
  495. public function getAppointmentsPendingDecisionAck() {
  496. return Appointment::where('pro_id', $this->id)
  497. ->where('is_decision_acknowledgement_from_appointment_pro_pending', true)
  498. ->where('raw_date', '>=', DB::raw('NOW()'))
  499. ->orderBy('raw_date', 'asc')
  500. ->get();
  501. }
  502. public function getAppointmentsPendingTimeChangeAck() {
  503. return Appointment::where('pro_id', $this->id)
  504. ->where('is_time_change_acknowledgement_from_appointment_pro_pending', true)
  505. ->where('raw_date', '>=', DB::raw('NOW()'))
  506. ->orderBy('raw_date', 'asc')
  507. ->get();
  508. }
  509. public function getAccessibleClientsQuery($_search = false) {
  510. $proID = $this->id;
  511. $query = Client::whereNull('shadow_pro_id');
  512. if ($this->pro_type === 'ADMIN' && ($_search ? $this->can_see_any_client_via_search : $this->can_see_all_clients_in_list)) {
  513. $query = $query->where('id', '>', 0);
  514. } else {
  515. $query = $query->where(function ($q) use ($proID) {
  516. $q->where('mcp_pro_id', $proID)
  517. ->orWhere('cm_pro_id', $proID)
  518. ->orWhere('rmm_pro_id', $proID)
  519. ->orWhere('rme_pro_id', $proID)
  520. ->orWhere('physician_pro_id', $proID)
  521. ->orWhere('default_na_pro_id', $proID)
  522. ->orWhereRaw('id IN (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = ?)', [$proID])
  523. ->orWhereRaw('id IN (SELECT client_id FROM appointment WHERE status NOT IN (\'CANCELLED\') AND pro_id = ?)', [$proID])
  524. ->orWhereRaw('id IN (SELECT mcp_pro_id FROM client_program WHERE client_id = client.id AND is_active = TRUE)')
  525. ->orWhereRaw('id IN (SELECT manager_pro_id FROM client_program WHERE client_id = client.id AND is_active = TRUE)')
  526. ->orWhereRaw('id IN (SELECT client_id FROM note WHERE ally_pro_id = ? AND is_cancelled = FALSE)', [$proID]);;
  527. });
  528. }
  529. return $query;
  530. }
  531. public function canAccess($_patientUid) {
  532. $proID = $this->id;
  533. if ($this->pro_type === 'ADMIN') {
  534. return true;
  535. }
  536. $canAccess = Client::select('uid')
  537. ->where('uid', $_patientUid)
  538. ->where(function ($q) use ($proID) {
  539. $q->where('mcp_pro_id', $proID)
  540. ->orWhere('cm_pro_id', $proID)
  541. ->orWhere('rmm_pro_id', $proID)
  542. ->orWhere('rme_pro_id', $proID)
  543. ->orWhere('physician_pro_id', $proID)
  544. ->orWhere('default_na_pro_id', $proID)
  545. ->orWhereRaw('id IN (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = ?)', [$proID])
  546. ->orWhereRaw('id IN (SELECT client_id FROM appointment WHERE status NOT IN (\'CANCELLED\') AND pro_id = ?)', [$proID])
  547. ->orWhereRaw('id IN (SELECT mcp_pro_id FROM client_program WHERE client_id = client.id AND is_active = TRUE)')
  548. ->orWhereRaw('id IN (SELECT manager_pro_id FROM client_program WHERE client_id = client.id AND is_active = TRUE)')
  549. ->orWhereRaw('id IN (SELECT client_id FROM note WHERE ally_pro_id = ? AND is_cancelled = FALSE)', [$proID]);
  550. })->count();
  551. return !!$canAccess;
  552. }
  553. public function canAddCPMEntryForMeasurement(Measurement $measurement, Pro $pro)
  554. {
  555. // check if client has any programs where this measurement type is allowed
  556. $allowed = false;
  557. $client = $measurement->client;
  558. $clientPrograms = $client->clientPrograms;
  559. if($pro->pro_type !== 'ADMIN') {
  560. $clientPrograms = $clientPrograms->filter(function($_clientProgram) use ($pro) {
  561. return $_clientProgram->manager_pro_id === $pro->id;
  562. });
  563. }
  564. if(count($clientPrograms)) {
  565. foreach ($clientPrograms as $clientProgram) {
  566. if(strpos(strtolower($clientProgram->measurement_labels), '|' . strtolower($measurement->label) . '|') !== FALSE) {
  567. $allowed = true;
  568. break;
  569. }
  570. }
  571. }
  572. return $allowed ? $clientPrograms : FALSE;
  573. }
  574. public function getUnstampedMeasurementsFromCurrentMonth($_countOnly, $skip, $limit)
  575. {
  576. date_default_timezone_set('US/Eastern');
  577. $start = strtotime(date('Y-m-01'));
  578. $end = date_add(date_create(date('Y-m-01')), date_interval_create_from_date_string("1 month"))->getTimestamp();
  579. $start *= 1000;
  580. $end *= 1000;
  581. $measurementsQuery = Measurement::where('is_removed', false)
  582. ->join('client', 'client.id', '=', 'measurement.client_id')
  583. ->whereNotNull('measurement.client_bdt_measurement_id')
  584. ->whereNotNull('measurement.ts')
  585. ->where('measurement.is_cellular_zero', false)
  586. ->where('measurement.ts', '>=', $start)
  587. ->where('measurement.ts', '<', $end)
  588. ->whereIn('measurement.client_id', $this->getMyClientIds())
  589. ->where(function ($q) {
  590. $q
  591. ->where(function ($q2) {
  592. $q2
  593. ->where('client.mcp_pro_id', $this->id)
  594. ->where('measurement.has_been_stamped_by_mcp', false);
  595. })
  596. ->orWhere(function ($q2) {
  597. $q2
  598. ->where('client.default_na_pro_id', $this->id)
  599. ->where('measurement.has_been_stamped_by_non_hcp', false);
  600. })
  601. ->orWhere(function ($q2) {
  602. $q2
  603. ->where('client.rmm_pro_id', $this->id)
  604. ->where('measurement.has_been_stamped_by_rmm', false);
  605. })
  606. ->orWhere(function ($q2) {
  607. $q2
  608. ->where('client.rme_pro_id', $this->id)
  609. ->where('measurement.has_been_stamped_by_rme', false);
  610. });
  611. });
  612. if($_countOnly) {
  613. return $measurementsQuery->count();
  614. }
  615. $x = [];
  616. $measurements = $measurementsQuery
  617. ->orderBy('ts', 'desc')
  618. ->skip($skip)
  619. ->take($limit)
  620. ->get();
  621. // eager load stuff needed in JS
  622. foreach ($measurements as $measurement) {
  623. // if ($measurement->client_bdt_measurement_id) {
  624. // $measurement->bdtMeasurement = $measurement->clientBDTMeasurement->measurement;
  625. // }
  626. unset($measurement->clientBDTMeasurement); // we do not need this travelling to the frontend
  627. $client = [
  628. "uid" => $measurement->client->uid,
  629. "name" => $measurement->client->displayName(),
  630. ];
  631. $measurement->patient = $client;
  632. $measurement->careMonth = $measurement->client->currentCareMonth();
  633. $measurement->timestamp = friendlier_date_time($measurement->created_at);
  634. unset($measurement->client); // we do not need this travelling to the frontend
  635. if(@$measurement->detail_json) unset($measurement->detail_json);
  636. if(@$measurement->canvas_data) unset($measurement->canvas_data);
  637. if(@$measurement->latest_measurements) unset($measurement->latest_measurements);
  638. if(@$measurement->info_lines) unset($measurement->info_lines);
  639. if(@$measurement->canvas_data_backup) unset($measurement->canvas_data_backup);
  640. if(@$measurement->migrated_canvas_data_backup) unset($measurement->migrated_canvas_data_backup);
  641. // if($measurement->label == 'SBP' || $measurement->label = 'DBP'){
  642. // continue;
  643. // }
  644. $x[] = $measurement;
  645. }
  646. // dd($measurements);
  647. return $measurements;
  648. }
  649. public function getMeasurements($_onlyUnstamped = true)
  650. {
  651. $measurementsQuery = Measurement::where('is_removed', false);
  652. if ($this->pro_type != 'ADMIN') {
  653. $measurementsQuery
  654. ->whereIn('client_id', $this->getMyClientIds());
  655. }
  656. if ($_onlyUnstamped) {
  657. $measurementsQuery
  658. ->whereNotNull('client_bdt_measurement_id')
  659. ->whereNotNull('ts')
  660. ->where('is_cellular_zero', false)
  661. ->where(function ($q) {
  662. $q->whereNull('status')
  663. ->orWhere(function ($q2) {
  664. $q2->where('status', '<>', 'ACK')
  665. ->where('status', '<>', 'INVALID_ACK');
  666. });
  667. });
  668. }
  669. $x = [];
  670. $measurements = $measurementsQuery->orderBy('ts', 'desc')->paginate(50);
  671. // eager load stuff needed in JS
  672. foreach ($measurements as $measurement) {
  673. // if ($measurement->client_bdt_measurement_id) {
  674. // $measurement->bdtMeasurement = $measurement->clientBDTMeasurement->measurement;
  675. // }
  676. unset($measurement->clientBDTMeasurement); // we do not need this travelling to the frontend
  677. $client = [
  678. "uid" => $measurement->client->uid,
  679. "name" => $measurement->client->displayName(),
  680. ];
  681. $measurement->patient = $client;
  682. $measurement->careMonth = $measurement->client->currentCareMonth();
  683. $measurement->timestamp = friendly_date_time($measurement->created_at);
  684. unset($measurement->client); // we do not need this travelling to the frontend
  685. // if($measurement->label == 'SBP' || $measurement->label = 'DBP'){
  686. // continue;
  687. // }
  688. $x[] = $measurement;
  689. }
  690. return $measurements;
  691. }
  692. public function companyPros()
  693. {
  694. return $this->hasMany(CompanyPro::class, 'pro_id', 'id')
  695. ->where('is_active', true);
  696. }
  697. public function companyProPayers()
  698. {
  699. return $this->hasMany(CompanyProPayer::class, 'pro_id', 'id');
  700. }
  701. public function isAssociatedWithMCPayer() {
  702. $companyProPayers = $this->companyProPayers;
  703. $foundMC = false;
  704. if($companyProPayers) {
  705. foreach ($companyProPayers as $companyProPayer) {
  706. if($companyProPayer->payer && $companyProPayer->payer->is_medicare) {
  707. $foundMC = true;
  708. break;
  709. }
  710. }
  711. }
  712. return $foundMC;
  713. }
  714. public function isAssociatedWithNonMCPayer($_payerID) {
  715. $companyProPayers = $this->companyProPayers;
  716. $foundNonMC = false;
  717. if($companyProPayers) {
  718. foreach ($companyProPayers as $companyProPayer) {
  719. if($companyProPayer->payer && !$companyProPayer->payer->is_medicare && $companyProPayer->payer->id === $_payerID) {
  720. $foundNonMC = true;
  721. break;
  722. }
  723. }
  724. }
  725. return $foundNonMC;
  726. }
  727. public function companyLocations() {
  728. $companyProPayers = $this->companyProPayers;
  729. $companyIDs = [];
  730. foreach ($companyProPayers as $companyProPayer) {
  731. $companyIDs[] = $companyProPayer->company_id;
  732. }
  733. $locations = [];
  734. if(count($companyIDs)) {
  735. $locations = CompanyLocation::whereIn('id', $companyIDs)->get();
  736. }
  737. return $locations;
  738. }
  739. public function shadowClient() {
  740. return $this->hasOne(Client::class, 'id', 'shadow_client_id');
  741. }
  742. public function defaultCompanyPro() {
  743. return $this->hasOne(CompanyPro::class, 'id', 'default_company_pro_id');
  744. }
  745. public function currentNotePickupForProcessing() {
  746. return $this->hasOne(NotePickupForProcessing::class, 'id', 'current_note_pickup_for_processing_id');
  747. }
  748. public function get_patients_not_seen_in_45_days_count_as_mcp(){
  749. return 0;
  750. }
  751. }