Pro.php 22 KB

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