Pro.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  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. ->orWhereRaw('id IN (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = ?)', [$proID])
  277. ->orWhereRaw('id IN (SELECT client_id FROM appointment WHERE status NOT IN (\'CANCELLED\', \'ABANDONED\') AND pro_id = ?)', [$proID])
  278. ->orWhereRaw('id IN (SELECT mcp_pro_id FROM client_program WHERE client_id = client.id AND is_active = TRUE)')
  279. ->orWhereRaw('id IN (SELECT manager_pro_id FROM client_program WHERE client_id = client.id AND is_active = TRUE)')
  280. ->orWhereRaw('id IN (SELECT client_id FROM note WHERE ally_pro_id = ? AND is_cancelled = FALSE)', [$proID]);;
  281. });
  282. }
  283. return $query;
  284. }
  285. public function canAccess($_patientUid) {
  286. $proID = $this->id;
  287. if ($this->pro_type === 'ADMIN') {
  288. return true;
  289. }
  290. $canAccess = Client::select('uid')
  291. ->where('uid', $_patientUid)
  292. ->where(function ($q) use ($proID) {
  293. $q->where('mcp_pro_id', $proID)
  294. ->orWhere('cm_pro_id', $proID)
  295. ->orWhere('rmm_pro_id', $proID)
  296. ->orWhere('rme_pro_id', $proID)
  297. ->orWhere('physician_pro_id', $proID)
  298. ->orWhereRaw('id IN (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = ?)', [$proID])
  299. ->orWhereRaw('id IN (SELECT client_id FROM appointment WHERE status NOT IN (\'CANCELLED\', \'ABANDONED\') AND pro_id = ?)', [$proID])
  300. ->orWhereRaw('id IN (SELECT mcp_pro_id FROM client_program WHERE client_id = client.id AND is_active = TRUE)')
  301. ->orWhereRaw('id IN (SELECT manager_pro_id FROM client_program WHERE client_id = client.id AND is_active = TRUE)')
  302. ->orWhereRaw('id IN (SELECT client_id FROM note WHERE ally_pro_id = ? AND is_cancelled = FALSE)', [$proID]);
  303. })->count();
  304. return !!$canAccess;
  305. }
  306. public function canAddCPMEntryForMeasurement(Measurement $measurement, Pro $pro)
  307. {
  308. // check if client has any programs where this measurement type is allowed
  309. $allowed = false;
  310. $client = $measurement->client;
  311. $clientPrograms = $client->clientPrograms;
  312. if($pro->pro_type !== 'ADMIN') {
  313. $clientPrograms = $clientPrograms->filter(function($_clientProgram) use ($pro) {
  314. return $_clientProgram->manager_pro_id === $pro->id;
  315. });
  316. }
  317. if(count($clientPrograms)) {
  318. foreach ($clientPrograms as $clientProgram) {
  319. if(strpos(strtolower($clientProgram->measurement_labels), '|' . strtolower($measurement->label) . '|') !== FALSE) {
  320. $allowed = true;
  321. break;
  322. }
  323. }
  324. }
  325. return $allowed ? $clientPrograms : FALSE;
  326. }
  327. public function getMeasurements($_onlyUnstamped = true)
  328. {
  329. $measurementsQuery = Measurement::where('is_removed', false);
  330. if ($this->pro_type != 'ADMIN') {
  331. $measurementsQuery
  332. ->whereIn('client_id', $this->getMyClientIds());
  333. }
  334. if ($_onlyUnstamped) {
  335. $measurementsQuery
  336. ->whereNotNull('client_bdt_measurement_id')
  337. ->whereNotNull('ts')
  338. ->where('is_cellular_zero', false)
  339. ->where(function ($q) {
  340. $q->whereNull('status')
  341. ->orWhere(function ($q2) {
  342. $q2->where('status', '<>', 'ACK')
  343. ->where('status', '<>', 'INVALID_ACK');
  344. });
  345. });
  346. }
  347. $x = [];
  348. $measurements = $measurementsQuery->orderBy('ts', 'desc')->paginate(50);
  349. // eager load stuff needed in JS
  350. foreach ($measurements as $measurement) {
  351. // if ($measurement->client_bdt_measurement_id) {
  352. // $measurement->bdtMeasurement = $measurement->clientBDTMeasurement->measurement;
  353. // }
  354. unset($measurement->clientBDTMeasurement); // we do not need this travelling to the frontend
  355. $client = [
  356. "uid" => $measurement->client->uid,
  357. "name" => $measurement->client->displayName(),
  358. ];
  359. $measurement->patient = $client;
  360. $measurement->careMonth = $measurement->client->currentCareMonth();
  361. $measurement->timestamp = friendly_date_time($measurement->created_at);
  362. unset($measurement->client); // we do not need this travelling to the frontend
  363. // if($measurement->label == 'SBP' || $measurement->label = 'DBP'){
  364. // continue;
  365. // }
  366. $x[] = $measurement;
  367. }
  368. return $measurements;
  369. }
  370. public function companyProPayers()
  371. {
  372. return $this->hasMany(CompanyProPayer::class, 'pro_id', 'id');
  373. }
  374. public function isAssociatedWithMCPayer() {
  375. $companyProPayers = $this->companyProPayers;
  376. $foundMC = false;
  377. if($companyProPayers) {
  378. foreach ($companyProPayers as $companyProPayer) {
  379. if($companyProPayer->payer && $companyProPayer->payer->is_medicare) {
  380. $foundMC = true;
  381. break;
  382. }
  383. }
  384. }
  385. return $foundMC;
  386. }
  387. public function isAssociatedWithNonMCPayer($_payerID) {
  388. $companyProPayers = $this->companyProPayers;
  389. $foundNonMC = false;
  390. if($companyProPayers) {
  391. foreach ($companyProPayers as $companyProPayer) {
  392. if($companyProPayer->payer && !$companyProPayer->payer->is_medicare && $companyProPayer->payer->id === $_payerID) {
  393. $foundNonMC = true;
  394. break;
  395. }
  396. }
  397. }
  398. return $foundNonMC;
  399. }
  400. public function companyLocations() {
  401. $companyProPayers = $this->companyProPayers;
  402. $companyIDs = [];
  403. foreach ($companyProPayers as $companyProPayer) {
  404. $companyIDs[] = $companyProPayer->company_id;
  405. }
  406. $locations = [];
  407. if(count($companyIDs)) {
  408. $locations = CompanyLocation::whereIn('id', $companyIDs)->get();
  409. }
  410. return $locations;
  411. }
  412. public function shadowClient() {
  413. return $this->hasOne(Client::class, 'id', 'shadow_client_id');
  414. }
  415. }