Pro.php 22 KB

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