Pro.php 22 KB

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