Pro.php 22 KB

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