Pro.php 17 KB

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