Pro.php 22 KB

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