Pro.php 21 KB

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