Pro.php 22 KB

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