Pro.php 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407
  1. <?php
  2. namespace App\Models;
  3. # use Illuminate\Database\Eloquent\Model;
  4. use App\Helpers\TimeLine;
  5. use DateTime;
  6. use Exception;
  7. use Illuminate\Support\Facades\DB;
  8. class Pro extends Model
  9. {
  10. protected $table = 'pro';
  11. public function displayName($_flat = false) {
  12. $name = [];
  13. if(!empty($this->name_display)) return $this->name_display;
  14. $sep = ", ";
  15. if($_flat) {
  16. if(!empty($this->name_first)) $name[] = $this->name_first;
  17. if(!empty($this->name_last)) $name[] = $this->name_last;
  18. $sep = ' ';
  19. }
  20. else {
  21. if(!empty($this->name_last)) $name[] = $this->name_last;
  22. if(!empty($this->name_first)) $name[] = $this->name_first;
  23. }
  24. if(!count($name)) {
  25. $name = $this->name_display;
  26. }
  27. else {
  28. $name = implode($sep, $name);
  29. }
  30. return $name;
  31. }
  32. public function initials() {
  33. $characters = [];
  34. if(!empty($this->name_first)) $characters[] = $this->name_first[0];
  35. if(!empty($this->name_last)) $characters[] = $this->name_last[0];
  36. return strtolower(implode("", $characters));
  37. }
  38. public function debitBills()
  39. {
  40. return $this->hasMany(Bill::class, 'debit_pro_id');
  41. }
  42. public function cmBills()
  43. {
  44. return $this->hasMany(Bill::class, 'cm_pro_id');
  45. }
  46. public function hcpBills()
  47. {
  48. return $this->hasMany(Bill::class, 'hcp_pro_id');
  49. }
  50. public function teamsWhereMcp()
  51. {
  52. return $this->hasMany(ProTeam::class, 'mcp_pro_id', 'id');
  53. }
  54. public function teamsWhereAssistant()
  55. {
  56. return $this->hasMany(ProTeam::class, 'assistant_pro_id', 'id');
  57. }
  58. public function isDefaultNA()
  59. {
  60. return $this->is_considered_for_dna && !$this->is_hcp;
  61. }
  62. public function lastPayment() {
  63. return ProTransaction
  64. ::where('pro_id', $this->id)
  65. ->where('plus_or_minus', 'PLUS')
  66. ->orderBy('created_at', 'desc')
  67. ->first();
  68. }
  69. public function hasRates() {
  70. $numRates = ProRate::where('is_active', true)->where('pro_id', $this->id)->count();
  71. return $numRates > 0;
  72. }
  73. public function cmRates() {
  74. return ProRate::distinct('code')
  75. ->where('is_active', true)
  76. ->where('pro_id', $this->id)
  77. ->where('code', 'LIKE', 'CM%')
  78. ->get();
  79. }
  80. public function rmRates() {
  81. return ProRate::distinct('code')
  82. ->where('is_active', true)
  83. ->where('pro_id', $this->id)
  84. ->where('code', 'LIKE', 'RM%')
  85. ->get();
  86. }
  87. public function noteRates() {
  88. return ProRate::distinct('code')
  89. ->where('is_active', true)
  90. ->where('pro_id', $this->id)
  91. ->where('code', 'NOT LIKE', 'CM%')
  92. ->where('code', 'NOT LIKE', 'RM%')
  93. ->where('responsibility', '<>', 'GENERIC')
  94. ->where('responsibility', '<>', 'NA')
  95. ->get();
  96. }
  97. public function genericRates() {
  98. return ProRate::distinct('code')
  99. ->where('is_active', true)
  100. ->where('pro_id', $this->id)
  101. ->where('responsibility', 'GENERIC')
  102. ->get();
  103. }
  104. public function recentDebits() {
  105. return ProTransaction
  106. ::where('pro_id', $this->id)
  107. ->where('plus_or_minus', 'PLUS')
  108. ->orderBy('created_at', 'desc')
  109. ->skip(0)->take(4)->get();
  110. }
  111. public function shortcuts() {
  112. return $this->hasMany(ProTextShortcut::class, 'pro_id')->where('is_removed', false);
  113. }
  114. public function allShortcuts() {
  115. $myId = $this->id;
  116. $shortcuts = ProTextShortcut::where('is_removed', false)
  117. ->where(function ($query2) use ($myId) {
  118. $query2
  119. ->where('pro_id', $myId)
  120. ->orWhereNull('pro_id');
  121. })
  122. ->orderBy('shortcut')
  123. ->get();
  124. return $shortcuts;
  125. }
  126. public function noteTemplates() {
  127. return $this->hasMany(NoteTemplatePro::class, 'pro_id')
  128. ->where('is_removed', false)
  129. ->orderBy('position_index', 'asc');
  130. }
  131. public function visitTemplates() {
  132. if($this->pro_type == 'ADMIN'){
  133. return VisitTemplate::where('is_active' , true)->get();
  134. }
  135. $allAccessibleVisitTemplatesIDs = VisitTemplate::where('is_accessible_to_all', true)->where('is_active', true)->pluck('id')->toArray();
  136. $accesses = VisitTemplateAccess::where('pro_id', $this->id)->where('is_active', true)->pluck('visit_template_id')->toArray();
  137. $allAllowedVisitTemplatesIDs = array_unique(array_merge($allAccessibleVisitTemplatesIDs, $accesses));
  138. return VisitTemplate::whereIn('id', $allAllowedVisitTemplatesIDs)->get();
  139. }
  140. public function currentWork() {
  141. return ProClientWork::where('pro_id', $this->id)->where('is_active', true)->first();
  142. }
  143. public function isWorkingOnClient($_client) {
  144. $count = ProClientWork::where('pro_id', $this->id)->where('client_id', $_client->id)->where('is_active', true)->count();
  145. return $count > 0;
  146. }
  147. public function canvasCustomItems($_key) {
  148. return ClientCanvasDataCustomItem::where('key', $_key)
  149. ->where('pro_id', $this->id)
  150. ->where('is_removed', false)
  151. ->orderBy('label')
  152. ->get();
  153. }
  154. /**
  155. * @param $_start - YYYY-MM-DD
  156. * @param $_end - YYYY-MM-DD
  157. * @param string $_timezone - defaults to EASTERN
  158. * @param string $_availableBG - defaults to #00a
  159. * @param string $_unavailableBG - defaults to #a00
  160. * @return array
  161. * @throws Exception
  162. */
  163. public function getAvailabilityEvents($_start, $_end, $_timezone = 'EASTERN', $_availableBG = '#00a', $_unavailableBG = '#a00') {
  164. $_start .= ' 00:00:00';
  165. $_end .= ' 23:59:59';
  166. // get availability data
  167. $proGenAvail = ProGeneralAvailability
  168. ::where('is_cancelled', false)
  169. ->where('pro_id', $this->id)
  170. ->get();
  171. $proSpecAvail = ProSpecificAvailability
  172. ::where('is_cancelled', false)
  173. ->where('pro_id', $this->id)
  174. ->where(function ($query) use ($_start, $_end) {
  175. $query
  176. ->where(function ($query2) use ($_start, $_end) {
  177. $query2
  178. ->where('start_time', '>=', $_start)
  179. ->where('start_time', '<=', $_end);
  180. })
  181. ->orWhere(function ($query2) use ($_start, $_end) {
  182. $query2
  183. ->where('end_time', '>=', $_start)
  184. ->where('end_time', '<=', $_end);
  185. });
  186. })
  187. ->get();
  188. $proSpecUnavail = ProSpecificUnavailability
  189. ::where('is_cancelled', false)
  190. ->where('pro_id', $this->id)
  191. ->where(function ($query) use ($_start, $_end) {
  192. $query
  193. ->where(function ($query2) use ($_start, $_end) {
  194. $query2
  195. ->where('start_time', '>=', $_start)
  196. ->where('start_time', '<=', $_end);
  197. })
  198. ->orWhere(function ($query2) use ($_start, $_end) {
  199. $query2
  200. ->where('end_time', '>=', $_start)
  201. ->where('end_time', '<=', $_end);
  202. });
  203. })
  204. ->get();
  205. // default GA
  206. // if no gen avail, assume mon to fri, 9 to 7
  207. /*if (count($proGenAvail) === 0) {
  208. $dayNames = ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY'];
  209. foreach ($dayNames as $dayName) {
  210. $item = new \stdClass();
  211. $item->day_of_week = $dayName;
  212. $item->timezone = $_timezone;
  213. $item->start_time = '09:00:00';
  214. $item->end_time = '18:00:00';
  215. $proGenAvail->push($item);
  216. }
  217. }*/
  218. // create timeline
  219. $phpTZ = appTZtoPHPTZ($_timezone);
  220. $phpTZObject = new \DateTimeZone($phpTZ);
  221. $startDate = new \DateTime($_start, $phpTZObject);
  222. $endDate = new \DateTime($_end, $phpTZObject);
  223. $proTimeLine = new TimeLine($startDate, $endDate);
  224. // General availability
  225. $period = new \DatePeriod($startDate, \DateInterval::createFromDateString('1 day'), $endDate);
  226. $days = [];
  227. foreach ($period as $day) {
  228. $days[] = [
  229. "day" => strtoupper($day->format("l")), // SUNDAY, etc.
  230. "date" => $day->format("Y-m-d"), // 2020-10-04, etc.
  231. ];
  232. }
  233. foreach ($days as $day) {
  234. $proGenAvailForTheDay = $proGenAvail->filter(function ($record) use ($day) {
  235. return $record->day_of_week === $day["day"];
  236. });
  237. foreach ($proGenAvailForTheDay as $ga) {
  238. $gaStart = new \DateTime($day["date"], new \DateTimeZone(appTZtoPHPTZ($ga->timezone)));
  239. $parts = explode(":", $ga->start_time);
  240. $gaStart->setTime(intval($parts[0]), intval($parts[1]), intval($parts[2]));
  241. $gaStart->setTimezone($phpTZObject);
  242. $gaEnd = new \DateTime($day["date"], new \DateTimeZone(appTZtoPHPTZ($ga->timezone)));
  243. $parts = explode(":", $ga->end_time);
  244. $gaEnd->setTime(intval($parts[0]), intval($parts[1]), intval($parts[2]));
  245. $gaEnd->setTimezone($phpTZObject);
  246. $proTimeLine->addAvailability($gaStart, $gaEnd);
  247. }
  248. }
  249. // specific availability
  250. foreach ($proSpecAvail as $sa) {
  251. $saStart = new \DateTime($sa->start_time, new \DateTimeZone(appTZtoPHPTZ($sa->timezone)));
  252. $saStart->setTimezone($phpTZObject);
  253. $saEnd = new \DateTime($sa->end_time, new \DateTimeZone(appTZtoPHPTZ($sa->timezone)));
  254. $saEnd->setTimezone($phpTZObject);
  255. $proTimeLine->addAvailability($saStart, $saEnd);
  256. }
  257. // specific unavailability
  258. foreach ($proSpecUnavail as $sua) {
  259. $suaStart = new \DateTime($sua->start_time, new \DateTimeZone(appTZtoPHPTZ($sua->timezone)));
  260. $suaStart->setTimezone($phpTZObject);
  261. $suaEnd = new \DateTime($sua->end_time, new \DateTimeZone(appTZtoPHPTZ($sua->timezone)));
  262. $suaEnd->setTimezone($phpTZObject);
  263. $proTimeLine->removeAvailability($suaStart, $suaEnd);
  264. }
  265. $events = [];
  266. // availability
  267. foreach ($proTimeLine->getAvailable() as $item) {
  268. $eStart = new \DateTime('@' . $item->start);
  269. $eStart->setTimezone($phpTZObject);
  270. $eEnd = new \DateTime('@' . $item->end);
  271. $eEnd->setTimezone($phpTZObject);
  272. $events[] = [
  273. "type" => "availability",
  274. "start" => $eStart->format('Y-m-d H:i:s'),
  275. "end" => $eEnd->format('Y-m-d H:i:s'),
  276. "editable" => false,
  277. "backgroundColor" => $_availableBG
  278. ];
  279. }
  280. // unavailability
  281. foreach ($proTimeLine->getUnavailable() as $item) {
  282. $eStart = new \DateTime('@' . $item->start);
  283. $eStart->setTimezone($phpTZObject);
  284. $eEnd = new \DateTime('@' . $item->end);
  285. $eEnd->setTimezone($phpTZObject);
  286. $events[] = [
  287. "type" => "unavailability",
  288. "start" => $eStart->format('Y-m-d H:i:s'),
  289. "end" => $eEnd->format('Y-m-d H:i:s'),
  290. "editable" => false,
  291. "backgroundColor" => $_unavailableBG
  292. ];
  293. }
  294. return $events;
  295. }
  296. public function getMyClientIds($_search = false) {
  297. $clients = $this->getAccessibleClientsQuery($_search)->get();
  298. $clientIds = [];
  299. foreach($clients as $client){
  300. $clientIds[] = $client->id;
  301. }
  302. return $clientIds;
  303. }
  304. public function favoritesByCategory($_category) {
  305. return ProFavorite::where('pro_id', $this->id)
  306. ->where('is_removed', false)
  307. ->where('category', $_category)
  308. ->orderBy('category', 'asc')
  309. ->orderBy('position_index', 'asc')
  310. ->get();
  311. }
  312. public function favoritesByCategoryDecoded($_category) {
  313. $favorites = ProFavorite::where('pro_id', $this->id)
  314. ->where('is_removed', false)
  315. ->where('category', $_category)
  316. ->orderBy('category', 'asc')
  317. ->orderBy('position_index', 'asc')
  318. ->get();
  319. foreach ($favorites as $favorite) {
  320. if ($favorite->data) {
  321. $favorite->data = json_decode($favorite->data);
  322. }
  323. }
  324. return $favorites;
  325. }
  326. function get_patients_count_as_admin() {
  327. $query = Client::whereNull('shadow_pro_id');
  328. return $query->where('is_active', true)
  329. ->where(function ($q) {
  330. $q->whereNull('client_engagement_status_category')
  331. ->orWhere('client_engagement_status_category', '<>', 'DUMMY');
  332. })->count();
  333. }
  334. function get_patients_count_as_mcp() {
  335. $query = Client::whereNull('shadow_pro_id');
  336. return $query->where('mcp_pro_id', $this->id)
  337. ->where(function ($q) {
  338. $q->whereNull('client_engagement_status_category')
  339. ->orWhere('client_engagement_status_category', '<>', 'DUMMY');
  340. })->count();
  341. }
  342. function get_new_patients_awaiting_visit_count_as_mcp() {
  343. $query = Client::whereNull('shadow_pro_id');
  344. return $query->where('mcp_pro_id', $this->id)
  345. ->where('has_mcp_done_onboarding_visit', '!=', 'YES')
  346. ->count();
  347. }
  348. function get_new_patients_awaiting_visit_count_as_admin() {
  349. $query = Client::whereNull('shadow_pro_id');
  350. return $query->where('has_mcp_done_onboarding_visit', '!=', 'YES')
  351. ->where(function ($q) {
  352. $q->whereNull('client_engagement_status_category')
  353. ->orWhere('client_engagement_status_category', '<>', 'DUMMY');
  354. })
  355. ->count();
  356. }
  357. function get_notes_pending_signature_count_as_mcp() {
  358. return Note::where('hcp_pro_id', $this->id)
  359. ->where('is_cancelled', '<>', true)
  360. ->where('is_core_note', '<>', true)
  361. ->where('is_signed_by_hcp', '<>', true)
  362. ->count();
  363. }
  364. function get_notes_pending_signature_count_as_admin() {
  365. return Note::where('is_cancelled', '<>', true)
  366. ->where('is_core_note', '<>', true)
  367. ->where('is_signed_by_hcp', '<>', true)
  368. ->count();
  369. }
  370. function get_notes_pending_summary_suggestion_as_mcp_query(){
  371. $segmentsWithProposedSummarySuggestion = Segment::whereHas('proposedSegmentSummarySuggestion', function($sugQuery){
  372. return $sugQuery->where('status', '=', 'PENDING');
  373. })->get();
  374. $noteIDs = [];
  375. foreach($segmentsWithProposedSummarySuggestion as $seg){
  376. $noteIDs[] = $seg->note_id;
  377. }
  378. return Note::where('hcp_pro_id', $this->id)
  379. ->where('is_cancelled', '<>', true)
  380. ->where('is_core_note', '<>', true)
  381. ->where('is_signed_by_hcp', true)
  382. ->whereIn('id', $noteIDs);
  383. }
  384. function get_notes_rejected_summary_suggestion_as_mcp_query(){
  385. $segmentsWithProposedSummarySuggestion = Segment::whereHas('proposedSegmentSummarySuggestion', function($sugQuery){
  386. return $sugQuery->where('status', '=', 'REJECTED');
  387. })->get();
  388. $noteIDs = [];
  389. foreach($segmentsWithProposedSummarySuggestion as $seg){
  390. $noteIDs[] = $seg->note_id;
  391. }
  392. return Note::where('hcp_pro_id', $this->id)
  393. ->where('is_cancelled', '<>', true)
  394. ->where('is_core_note', '<>', true)
  395. ->where('is_signed_by_hcp', true)
  396. ->whereIn('id', $noteIDs);
  397. }
  398. function get_notes_pending_summary_suggestion_count_as_mcp(){
  399. return $this->get_notes_pending_summary_suggestion_as_mcp_query()->count();
  400. }
  401. function get_notes_pending_summary_suggestion_as_mcp(){
  402. return $this->get_notes_pending_summary_suggestion_as_mcp_query()->get();
  403. }
  404. function get_notes_rejected_summary_suggestion_count_as_mcp(){
  405. return $this->get_notes_rejected_summary_suggestion_as_mcp_query()->count();
  406. }
  407. function get_notes_rejected_summary_suggestion_as_mcp(){
  408. return $this->get_notes_rejected_summary_suggestion_as_mcp_query()->get();
  409. }
  410. function get_notes_pending_summary_suggestion_as_admin_query(){
  411. $segmentsWithProposedSummarySuggestion = Segment::whereHas('proposedSegmentSummarySuggestion', function($sugQuery){
  412. return $sugQuery->where('status', '=', 'PENDING');
  413. })->get();
  414. $noteIDs = [];
  415. foreach($segmentsWithProposedSummarySuggestion as $seg){
  416. $noteIDs[] = $seg->note_id;
  417. }
  418. return Note::where('is_cancelled', '<>', true)
  419. ->where('is_core_note', '<>', true)
  420. ->where('is_signed_by_hcp', true)
  421. ->whereIn('id', $noteIDs);
  422. }
  423. function get_notes_rejected_summary_suggestion_as_admin_query(){
  424. $segmentsWithProposedSummarySuggestion = Segment::whereHas('proposedSegmentSummarySuggestion', function($sugQuery){
  425. return $sugQuery->where('status', '=', 'REJECTED');
  426. })->get();
  427. $noteIDs = [];
  428. foreach($segmentsWithProposedSummarySuggestion as $seg){
  429. $noteIDs[] = $seg->note_id;
  430. }
  431. return Note::where('is_cancelled', '<>', true)
  432. ->where('is_core_note', '<>', true)
  433. ->where('is_signed_by_hcp', true)
  434. ->whereIn('id', $noteIDs);
  435. }
  436. function get_notes_pending_summary_suggestion_count_as_admin(){
  437. return $this->get_notes_pending_summary_suggestion_as_admin_query()->count();
  438. }
  439. function get_notes_pending_summary_suggestion_as_admin(){
  440. return $this->get_notes_pending_summary_suggestion_as_admin_query()->get();
  441. }
  442. function get_notes_rejected_summary_suggestion_count_as_admin(){
  443. return $this->get_notes_rejected_summary_suggestion_as_admin_query()->count();
  444. }
  445. function get_notes_rejected_summary_suggestion_as_admin(){
  446. return $this->get_notes_rejected_summary_suggestion_as_admin_query()->get();
  447. }
  448. function get_notes_pending_billing_count_as_mcp() {
  449. return Note::where('hcp_pro_id', $this->id)
  450. ->where('is_cancelled', '<>', true)
  451. ->where('is_signed_by_hcp', true)
  452. ->where('is_billing_marked_done', '<>', true)
  453. ->count();
  454. }
  455. function get_notes_pending_billing_count_as_admin() {
  456. return Note::where('is_cancelled', '<>', true)
  457. ->where('is_signed_by_hcp', true)
  458. ->where('is_billing_marked_done', '<>', true)
  459. ->count();
  460. }
  461. function get_measurements_awaiting_review_count_as_mcp() {
  462. $result = DB::select(DB::raw("
  463. SELECT SUM(rm_num_measurements_not_stamped_by_mcp) AS count
  464. FROM care_month
  465. WHERE mcp_pro_id = :pro_id
  466. AND rm_num_measurements_not_stamped_by_mcp IS NOT NULL
  467. AND rm_num_measurements_not_stamped_by_mcp > 0;
  468. "), ["pro_id" => $this->id]);
  469. if($result) return $result[0]->count;
  470. }
  471. function get_bills_pending_signature_count_as_mcp(){
  472. $pendingBillsToSign = Bill::where('bill_service_type', '<>', 'CARE_MONTH')->where(function ($query) {
  473. $query->where('hcp_pro_id', $this->id)->where('is_signed_by_hcp', false)->where('is_cancelled', false);
  474. })
  475. ->orWhere(function ($query) {
  476. $query->where('cm_pro_id', $this->id)->where('is_signed_by_cm', false)->where('is_cancelled', false);
  477. })->orWhere(function ($query) {
  478. $query->where('rme_pro_id', $this->id)->where('is_signed_by_rme', false)->where('is_cancelled', false);
  479. })->orWhere(function ($query) {
  480. $query->where('rmm_pro_id', $this->id)->where('is_signed_by_rmm', false)->where('is_cancelled', false);
  481. })->orWhere(function ($query) {
  482. $query->where('generic_pro_id', $this->id)->where('is_signed_by_generic_pro', false)->where('is_cancelled', false);
  483. })->count();
  484. return $pendingBillsToSign;
  485. }
  486. function get_incoming_reports_pending_signature_count_as_mcp() {
  487. return IncomingReport::where('hcp_pro_id', $this->id)
  488. ->where('has_hcp_pro_signed', '<>', true)
  489. ->where('is_entry_error', '<>', true)
  490. ->count();
  491. }
  492. function get_incoming_reports_pending_signature_count_as_admin() {
  493. return IncomingReport::where('has_hcp_pro_signed', '<>', true)
  494. ->where('is_entry_error', '<>', true)
  495. ->count();
  496. }
  497. function get_patients_without_appointment_query() {
  498. return Client::where('mcp_pro_id', $this->id)
  499. ->whereNull('today_mcp_appointment_date')
  500. ->where(function($q){
  501. $q->whereNull('next_mcp_appointment_id')
  502. ->orWhere('next_mcp_appointment_date', '<=', DB::raw('NOW()::DATE'));
  503. });
  504. }
  505. function get_patients_without_appointment_for_dna_query() {
  506. return Client::where('default_na_pro_id', $this->id)
  507. ->whereNull('today_mcp_appointment_date')
  508. ->where(function($q){
  509. $q->whereNull('next_mcp_appointment_id')
  510. ->orWhere('next_mcp_appointment_date', '<=', DB::raw('NOW()::DATE'));
  511. });
  512. }
  513. function get_patients_without_appointment_count_as_mcp() {
  514. return $this->get_patients_without_appointment_query()->count();
  515. }
  516. function get_patients_without_appointment_count_as_admin() {
  517. return Client::whereNull('shadow_pro_id')
  518. ->where('is_active', true)
  519. ->where(function ($q) {
  520. $q->whereNull('client_engagement_status_category')
  521. ->orWhere('client_engagement_status_category', '<>', 'DUMMY');
  522. })
  523. ->whereNull('today_mcp_appointment_date')
  524. ->where(function($q){
  525. $q->whereNull('next_mcp_appointment_id')
  526. ->orWhere('next_mcp_appointment_date', '<', DB::raw('NOW()::DATE'));
  527. })->count();
  528. }
  529. function get_patients_overdue_for_visit_query() {
  530. return Client::where('mcp_pro_id', $this->id)
  531. ->where(function($q){
  532. $q->whereNull('most_recent_completed_mcp_note_id')
  533. ->orWhere('most_recent_completed_mcp_note_date', '<', DB::raw("NOW()::DATE - INTERVAL '45 DAY'"));
  534. });
  535. }
  536. function get_patients_overdue_for_visit_for_dna_query() {
  537. return Client::where('default_na_pro_id', $this->id)
  538. ->where(function($q){
  539. $q->whereNull('most_recent_completed_mcp_note_id')
  540. ->orWhere('most_recent_completed_mcp_note_date', '<', DB::raw("NOW()::DATE - INTERVAL '45 DAY'"));
  541. });
  542. }
  543. function get_patients_overdue_count_as_mcp() {
  544. return $this->get_patients_overdue_for_visit_query()->count();
  545. }
  546. function get_patients_without_remote_measurement_in_48_hours_count_as_mcp() {
  547. return DB::select("SELECT COUNT(*) as count FROM client WHERE ((most_recent_cellular_measurement_at+ interval '48 hour')::timestamp < NOW() OR most_recent_cellular_measurement_id IS NULL) AND client.mcp_pro_id = :mcp_pro_id AND is_active IS TRUE", ['mcp_pro_id'=>$this->id])[0]->count;
  548. }
  549. function get_cancelled_appointments_pending_acknowledgement_count_as_mcp_query() {
  550. // SELECT * FROM appointment WHERE hcp_pro_id = :me.id AND status = 'REJECTED' AND wasAcknowledgedByAppointmentPro IS NOT TRUE;
  551. return Appointment::where('pro_id', $this->id)
  552. ->where('latest_confirmation_decision_enum', 'REJECTED')
  553. ->where('is_decision_acknowledgement_from_appointment_pro_pending', true);
  554. }
  555. function get_cancelled_appointments_pending_acknowledgement_count_as_mcp() {
  556. // SELECT * FROM appointment WHERE hcp_pro_id = :me.id AND status = 'REJECTED' AND wasAcknowledgedByAppointmentPro IS NOT TRUE;
  557. return $this->get_cancelled_appointments_pending_acknowledgement_count_as_mcp_query()->count();
  558. }
  559. function get_cancelled_bills_awaiting_review_count_as_mcp() {
  560. // SELECT * FROM bill WHERE bill_service_type = 'NOTE' AND is_cancelled IS TRUE AND isCancellationAcknowledged IS FALSE;
  561. return Bill::where('hcp_pro_id', $this->id)
  562. ->where('bill_service_type', 'NOTE')
  563. ->where('is_cancelled', true)
  564. ->where('is_cancellation_acknowledged', '<>', true)
  565. ->count();
  566. }
  567. function get_cancelled_supply_orders_awaiting_review_count_as_mcp() {
  568. // SELECT * FROM supply_order WHERE signed_by_pro_id = :me.id AND is_cancelled IS TRUE AND isCancellationAcknowledged IS NOT TRUE;
  569. return SupplyOrder::where('signed_by_pro_id', $this->id)
  570. ->where('is_cancelled', true)
  571. ->where('is_cancellation_acknowledged', '<>', true)
  572. ->count();
  573. }
  574. function get_erx_and_orders_awaiting_signature_count_as_mcp() {
  575. // SELECT * FROM erx WHERE hcp_pro_id = :me.id AND pro_declared_status <> 'CANCELLED' AND hasHcpProSigned IS NOT TRUE;
  576. return Erx::where('hcp_pro_id', $this->id)
  577. ->where('pro_declared_status', '<>', 'CANCELLED')
  578. ->where('has_hcp_pro_signed', '<>', true)
  579. ->count();
  580. }
  581. function get_supply_orders_awaiting_signature_count_as_mcp() {
  582. // SELECT supply_order.id FROM supply_order WHERE signed_by_pro_id IS NOT TRUE AND is_cancelled IS NOT TRUE AND created_by_pro_id = :me.id;
  583. return SupplyOrder::where('created_by_pro_id', $this->id)
  584. ->whereNull('signed_by_pro_id')
  585. ->where('is_cancelled', '<>', true)
  586. ->count();
  587. }
  588. function get_supply_orders_awaiting_shipment_count_as_mcp() {
  589. return SupplyOrder::where('created_by_pro_id', $this->id)
  590. ->where('is_signed_by_pro', true)
  591. ->where('is_cleared_for_shipment', true)
  592. ->whereNull('shipment_id')
  593. ->count();
  594. }
  595. function get_unsigned_incoming_reports_count_as_mcp() {
  596. return IncomingReport::where('hcp_pro_id', $this->id)
  597. ->whereRaw('(has_hcp_pro_signed IS NULL OR has_hcp_pro_signed = FALSE)')
  598. ->count();
  599. }
  600. function get_unsigned_rpm_bills_count_as_mcp() {
  601. $query = "
  602. SELECT count(distinct(care_month.id))
  603. FROM care_month join client on care_month.client_id = client.id join note mrnote on client.most_recent_completed_mcp_note_id = mrnote.id
  604. left join bill on care_month.mcp_rm_generic_bill_id = bill.id
  605. left join note mrmnote on mrmnote.id = (
  606. select max(n.id) from note n
  607. where
  608. n.client_id = client.id AND
  609. n.is_cancelled = FALSE AND
  610. (n.is_signed_by_hcp IS NOT NULL AND n.is_signed_by_hcp = TRUE) AND
  611. n.effective_dateest::date >= care_month.start_date::date AND
  612. n.effective_dateest::date < (care_month.start_date::date + INTERVAL '1 month')
  613. )
  614. WHERE
  615. care_month.mcp_pro_id = {$this->id}
  616. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  617. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  618. AND care_month.mcp_rm_generic_bill_id IS NOT NULL
  619. AND bill.is_signed_by_generic_pro = TRUE
  620. ";
  621. // dd($query);
  622. $count = DB::select($query);
  623. return $count[0]->count;
  624. }
  625. function get_unsigned_rpm_bills_count_as_rmm() {
  626. $query = "
  627. SELECT count(distinct(care_month.id))
  628. FROM care_month join client on care_month.client_id = client.id join note mrnote on client.most_recent_completed_mcp_note_id = mrnote.id
  629. left join bill on care_month.rmm_rm_generic_bill_id = bill.id
  630. left join note mrmnote on mrmnote.id = (
  631. select max(n.id) from note n
  632. where
  633. n.client_id = client.id AND
  634. n.is_cancelled = FALSE AND
  635. (n.is_signed_by_hcp IS NOT NULL AND n.is_signed_by_hcp = TRUE) AND
  636. n.effective_dateest::date >= care_month.start_date::date AND
  637. n.effective_dateest::date < (care_month.start_date::date + INTERVAL '1 month')
  638. )
  639. WHERE
  640. care_month.rmm_pro_id = {$this->id}
  641. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  642. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  643. AND care_month.rmm_rm_generic_bill_id IS NOT NULL
  644. AND bill.is_signed_by_generic_pro = TRUE
  645. ";
  646. // dd($query);
  647. $count = DB::select($query);
  648. return $count[0]->count;
  649. }
  650. function get_patients_awaiting_rpm_interaction_count_as_mcp() {
  651. $cmStartDate = date('Y-m-01');
  652. $query = "
  653. SELECT
  654. count(client.id)
  655. FROM
  656. client join care_month on client.id = care_month.client_id
  657. WHERE
  658. care_month.start_date = '{$cmStartDate}'
  659. AND care_month.is_client_enrolled_in_rm IS TRUE
  660. AND care_month.has_mcp_interacted_with_client_about_rm IS NOT TRUE
  661. AND care_month.mcp_pro_id = {$this->id}
  662. AND (client.client_engagement_status_category IS NULL OR client.client_engagement_status_category != 'DUMMY')
  663. AND client.name_first NOT ILIKE '%test%'
  664. AND client.name_last NOT ILIKE '%test%'
  665. ";
  666. $count = DB::select($query);
  667. return $count[0]->count;
  668. }
  669. function get_birthdays_today_as_mcp(){
  670. return;
  671. $queryClients = $this->performer()->pro->getAccessibleClientsQuery();
  672. $keyNumbers['patientsHavingBirthdayToday'] = $queryClients
  673. ->whereRaw('EXTRACT(DAY from dob) = ?', [date('d')])
  674. ->whereRaw('EXTRACT(MONTH from dob) = ?', [date('m')])
  675. ->count();
  676. $reimbursement = [];
  677. $reimbursement["currentBalance"] = $performer->pro->balance;
  678. $reimbursement["nextPaymentDate"] = '--';
  679. $lastPayment = ProTransaction::where('pro_id', $performerProID)->where('plus_or_minus', 'PLUS')->orderBy('created_at', 'DESC')->first();
  680. if ($lastPayment) {
  681. $reimbursement["lastPayment"] = $lastPayment->amount;
  682. $reimbursement["lastPaymentDate"] = $lastPayment->created_at;
  683. } else {
  684. $reimbursement["lastPayment"] = '--';
  685. $reimbursement["lastPaymentDate"] = '--';
  686. }
  687. }
  688. public function getAppointmentsPendingStatusChangeAck() {
  689. return Appointment::where('pro_id', $this->id)
  690. ->where('is_status_acknowledgement_from_appointment_pro_pending', true)
  691. //->where('raw_date', '>=', DB::raw('NOW()'))
  692. ->orderBy('raw_date', 'asc')
  693. ->get();
  694. }
  695. public function getAppointmentsPendingDecisionAck() {
  696. return Appointment::where('pro_id', $this->id)
  697. ->where('is_decision_acknowledgement_from_appointment_pro_pending', true)
  698. //->where('raw_date', '>=', DB::raw('NOW()'))
  699. ->orderBy('raw_date', 'asc')
  700. ->get();
  701. }
  702. public function getAppointmentsPendingTimeChangeAck() {
  703. return Appointment::where('pro_id', $this->id)
  704. ->where('is_time_change_acknowledgement_from_appointment_pro_pending', true)
  705. //->where('raw_date', '>=', DB::raw('NOW()'))
  706. ->orderBy('raw_date', 'asc')
  707. ->get();
  708. }
  709. public function getAccessibleClientsQuery($_search = false) {
  710. $proID = $this->id;
  711. $query = Client::whereNull('shadow_pro_id');
  712. if ($this->pro_type === 'ADMIN' && ($_search ? $this->can_see_any_client_via_search : $this->can_see_all_clients_in_list)) {
  713. $query = $query->where('id', '>', 0);
  714. } else {
  715. $query = $query->where(function ($q) use ($proID) {
  716. $q->where('mcp_pro_id', $proID)
  717. ->orWhere('cm_pro_id', $proID)
  718. ->orWhere('rmm_pro_id', $proID)
  719. ->orWhere('rme_pro_id', $proID)
  720. ->orWhere('physician_pro_id', $proID)
  721. ->orWhere('default_na_pro_id', $proID)
  722. ->orWhereRaw('id IN (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = ?)', [$proID])
  723. ->orWhereRaw('id IN (SELECT client_id FROM appointment WHERE status NOT IN (\'CANCELLED\') AND pro_id = ?)', [$proID])
  724. ->orWhereRaw('id IN (SELECT mcp_pro_id FROM client_program WHERE client_id = client.id AND is_active = TRUE)')
  725. ->orWhereRaw('id IN (SELECT manager_pro_id FROM client_program WHERE client_id = client.id AND is_active = TRUE)')
  726. ->orWhereRaw('id IN (SELECT client_id FROM note WHERE ally_pro_id = ? AND is_cancelled = FALSE)', [$proID]);;
  727. });
  728. }
  729. return $query;
  730. }
  731. public function canAccess($_patientUid) {
  732. $proID = $this->id;
  733. if ($this->pro_type === 'ADMIN') {
  734. return true;
  735. }
  736. $canAccess = Client::select('uid')
  737. ->where('uid', $_patientUid)
  738. ->where(function ($q) use ($proID) {
  739. $q->whereNull('mcp_pro_id')
  740. ->orWhere('mcp_pro_id', $proID)
  741. ->orWhere('cm_pro_id', $proID)
  742. ->orWhere('rmm_pro_id', $proID)
  743. ->orWhere('rme_pro_id', $proID)
  744. ->orWhere('physician_pro_id', $proID)
  745. ->orWhere('default_na_pro_id', $proID)
  746. ->orWhereRaw('id IN (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = ?)', [$proID])
  747. ->orWhereRaw('id IN (SELECT client_id FROM appointment WHERE status NOT IN (\'CANCELLED\') AND pro_id = ?)', [$proID])
  748. ->orWhereRaw('id IN (SELECT mcp_pro_id FROM client_program WHERE client_id = client.id AND is_active = TRUE)')
  749. ->orWhereRaw('id IN (SELECT manager_pro_id FROM client_program WHERE client_id = client.id AND is_active = TRUE)')
  750. ->orWhereRaw('id IN (SELECT client_id FROM note WHERE ally_pro_id = ? AND is_cancelled = FALSE)', [$proID])
  751. ->orWhereRaw('id IN (SELECT client_id FROM client_review_request WHERE pro_id = ? AND access_start_date <= NOW() AND access_end_date >= NOW() AND client_review_request.is_active IS true)', [$proID]);
  752. })->count();
  753. return !!$canAccess;
  754. }
  755. public function canAddCPMEntryForMeasurement(Measurement $measurement, Pro $pro)
  756. {
  757. // check if client has any programs where this measurement type is allowed
  758. $allowed = false;
  759. $client = $measurement->client;
  760. $clientPrograms = $client->clientPrograms;
  761. if($pro->pro_type !== 'ADMIN') {
  762. $clientPrograms = $clientPrograms->filter(function($_clientProgram) use ($pro) {
  763. return $_clientProgram->manager_pro_id === $pro->id;
  764. });
  765. }
  766. if(count($clientPrograms)) {
  767. foreach ($clientPrograms as $clientProgram) {
  768. if(strpos(strtolower($clientProgram->measurement_labels), '|' . strtolower($measurement->label) . '|') !== FALSE) {
  769. $allowed = true;
  770. break;
  771. }
  772. }
  773. }
  774. return $allowed ? $clientPrograms : FALSE;
  775. }
  776. public function getUnstampedMeasurementsFromCurrentMonth($_countOnly, $skip, $limit)
  777. {
  778. date_default_timezone_set('US/Eastern');
  779. $start = strtotime(date('Y-m-01'));
  780. $end = date_add(date_create(date('Y-m-01')), date_interval_create_from_date_string("1 month"))->getTimestamp();
  781. $start *= 1000;
  782. $end *= 1000;
  783. $measurementsQuery = Measurement::where('measurement.is_active', true)
  784. ->join('client', 'client.id', '=', 'measurement.client_id')
  785. ->whereNotNull('measurement.client_bdt_measurement_id')
  786. ->whereNotNull('measurement.ts')
  787. ->where('measurement.is_cellular_zero', false)
  788. ->where('measurement.ts', '>=', $start)
  789. ->where('measurement.ts', '<', $end)
  790. ->whereIn('measurement.client_id', $this->getMyClientIds())
  791. ->where(function ($q) {
  792. $q
  793. ->where(function ($q2) {
  794. $q2
  795. ->where('client.mcp_pro_id', $this->id)
  796. ->where('measurement.has_been_stamped_by_mcp', false);
  797. })
  798. ->orWhere(function ($q2) {
  799. $q2
  800. ->where('client.default_na_pro_id', $this->id)
  801. ->where('measurement.has_been_stamped_by_non_hcp', false);
  802. })
  803. ->orWhere(function ($q2) {
  804. $q2
  805. ->where('client.rmm_pro_id', $this->id)
  806. ->where('measurement.has_been_stamped_by_rmm', false);
  807. })
  808. ->orWhere(function ($q2) {
  809. $q2
  810. ->where('client.rme_pro_id', $this->id)
  811. ->where('measurement.has_been_stamped_by_rme', false);
  812. });
  813. });
  814. if($_countOnly) {
  815. return $measurementsQuery->count();
  816. }
  817. $x = [];
  818. $measurements = $measurementsQuery
  819. ->orderBy('ts', 'desc')
  820. ->skip($skip)
  821. ->take($limit)
  822. ->get();
  823. // eager load stuff needed in JS
  824. foreach ($measurements as $measurement) {
  825. // if ($measurement->client_bdt_measurement_id) {
  826. // $measurement->bdtMeasurement = $measurement->clientBDTMeasurement->measurement;
  827. // }
  828. unset($measurement->clientBDTMeasurement); // we do not need this travelling to the frontend
  829. $client = [
  830. "uid" => $measurement->client->uid,
  831. "name" => $measurement->client->displayName(),
  832. ];
  833. $measurement->patient = $client;
  834. $measurement->careMonth = $measurement->client->currentCareMonth();
  835. $measurement->timestamp = friendlier_date_time($measurement->created_at);
  836. unset($measurement->client); // we do not need this travelling to the frontend
  837. if(@$measurement->detail_json) unset($measurement->detail_json);
  838. if(@$measurement->canvas_data) unset($measurement->canvas_data);
  839. if(@$measurement->latest_measurements) unset($measurement->latest_measurements);
  840. if(@$measurement->info_lines) unset($measurement->info_lines);
  841. if(@$measurement->canvas_data_backup) unset($measurement->canvas_data_backup);
  842. if(@$measurement->migrated_canvas_data_backup) unset($measurement->migrated_canvas_data_backup);
  843. // if($measurement->label == 'SBP' || $measurement->label = 'DBP'){
  844. // continue;
  845. // }
  846. $x[] = $measurement;
  847. }
  848. // dd($measurements);
  849. return $measurements;
  850. }
  851. public function getMeasurements($_onlyUnstamped = true)
  852. {
  853. $measurementsQuery = Measurement::where('is_removed', false);
  854. if ($this->pro_type != 'ADMIN') {
  855. $measurementsQuery
  856. ->whereIn('client_id', $this->getMyClientIds());
  857. }
  858. if ($_onlyUnstamped) {
  859. $measurementsQuery
  860. ->whereNotNull('client_bdt_measurement_id')
  861. ->whereNotNull('ts')
  862. ->where('is_cellular_zero', false)
  863. ->where(function ($q) {
  864. $q->whereNull('status')
  865. ->orWhere(function ($q2) {
  866. $q2->where('status', '<>', 'ACK')
  867. ->where('status', '<>', 'INVALID_ACK');
  868. });
  869. });
  870. }
  871. $x = [];
  872. $measurements = $measurementsQuery->orderBy('ts', 'desc')->paginate(50);
  873. // eager load stuff needed in JS
  874. foreach ($measurements as $measurement) {
  875. // if ($measurement->client_bdt_measurement_id) {
  876. // $measurement->bdtMeasurement = $measurement->clientBDTMeasurement->measurement;
  877. // }
  878. unset($measurement->clientBDTMeasurement); // we do not need this travelling to the frontend
  879. $client = [
  880. "uid" => $measurement->client->uid,
  881. "name" => $measurement->client->displayName(),
  882. ];
  883. $measurement->patient = $client;
  884. $measurement->careMonth = $measurement->client->currentCareMonth();
  885. $measurement->timestamp = friendly_date_time($measurement->created_at);
  886. unset($measurement->client); // we do not need this travelling to the frontend
  887. // if($measurement->label == 'SBP' || $measurement->label = 'DBP'){
  888. // continue;
  889. // }
  890. $x[] = $measurement;
  891. }
  892. return $measurements;
  893. }
  894. public function companyPros()
  895. {
  896. return $this->hasMany(CompanyPro::class, 'pro_id', 'id')
  897. ->where('is_active', true);
  898. }
  899. public function companyProPayers()
  900. {
  901. return $this->hasMany(CompanyProPayer::class, 'pro_id', 'id');
  902. }
  903. public function isAssociatedWithMCPayer() {
  904. $companyProPayers = $this->companyProPayers;
  905. $foundMC = false;
  906. if($companyProPayers) {
  907. foreach ($companyProPayers as $companyProPayer) {
  908. if($companyProPayer->payer && $companyProPayer->payer->is_medicare) {
  909. $foundMC = true;
  910. break;
  911. }
  912. }
  913. }
  914. return $foundMC;
  915. }
  916. public function isAssociatedWithNonMCPayer($_payerID) {
  917. $companyProPayers = $this->companyProPayers;
  918. $foundNonMC = false;
  919. if($companyProPayers) {
  920. foreach ($companyProPayers as $companyProPayer) {
  921. if($companyProPayer->payer && !$companyProPayer->payer->is_medicare && $companyProPayer->payer->id === $_payerID) {
  922. $foundNonMC = true;
  923. break;
  924. }
  925. }
  926. }
  927. return $foundNonMC;
  928. }
  929. public function companyLocations() {
  930. $companyProPayers = $this->companyProPayers;
  931. $companyIDs = [];
  932. foreach ($companyProPayers as $companyProPayer) {
  933. $companyIDs[] = $companyProPayer->company_id;
  934. }
  935. $locations = [];
  936. if(count($companyIDs)) {
  937. $locations = CompanyLocation::whereIn('id', $companyIDs)->get();
  938. }
  939. return $locations;
  940. }
  941. public function shadowClient() {
  942. return $this->hasOne(Client::class, 'id', 'shadow_client_id');
  943. }
  944. public function defaultCompanyPro() {
  945. return $this->hasOne(CompanyPro::class, 'id', 'default_company_pro_id');
  946. }
  947. public function currentNotePickupForProcessing() {
  948. return $this->hasOne(NotePickupForProcessing::class, 'id', 'current_note_pickup_for_processing_id');
  949. }
  950. public function get_patients_not_seen_in_45_days_count_as_admin() {
  951. }
  952. public function get_patients_not_seen_in_45_days_count_as_mcp(){
  953. return 0;
  954. }
  955. public function get_open_tickets_count_as_mcp(){
  956. $self = $this;
  957. return Ticket::where(function ($q) use ($self) {
  958. $q->where('assigned_pro_id', $self->id)
  959. ->orWhere('manager_pro_id', $self->id)
  960. ->orWhere('ordering_pro_id', $self->id)
  961. ->orWhere('initiating_pro_id', $self->id);
  962. })
  963. ->where('category', 'other')
  964. ->where('is_open', true)
  965. ->count();
  966. }
  967. //DNA_DASHBOARD
  968. //queries
  969. private function patientsQueryAsDna(){
  970. // WHERE na_pro_id = :me.id
  971. return Client::where('default_na_pro_id', $this->id);
  972. }
  973. private function patientsAwaitingMcpVisitQueryAsDna(){
  974. // WHERE has_mcp_done_onboarding_visit <> 'YES'
  975. return Client::where('default_na_pro_id', $this->id)->where('has_mcp_done_onboarding_visit', '<>', 'YES');
  976. }
  977. private function patientsWithoutAppointmentQueryAsDna(){
  978. // WHERE today_mcp_appointment_date IS NULL AND next_mcp_appointment_date IS NULL
  979. return Client::where('default_na_pro_id', $this->id)
  980. ->whereNull('today_mcp_appointment_date')
  981. ->whereNull('next_mcp_appointment_date');
  982. }
  983. private function encountersPendingMyReviewQueryAsDna(){
  984. // WHERE ally_pro_id = me.id AND is_cancelled IS NOT TRUE AND is_signed_by_hcp IS TRUE AND is_signed_by_ally IS NOT TRUE;
  985. return Note::where('ally_pro_id', $this->id)
  986. ->where('is_cancelled', '<>', true)
  987. ->where('is_signed_by_hcp', true)
  988. ->where('is_signed_by_ally','<>', true);
  989. }
  990. private function encountersInProgressQueryAsDna(){
  991. // SELECT * FROM note WHERE ally_pro_id = me.id AND is_cancelled IS NOT TRUE AND is_signed_by_hcp IS NOT TRUE ORDER BY effective_dateest DESC, created_at DESC;
  992. return Note::where('ally_pro_id', $this->id)
  993. ->where('is_cancelled', '<>', true)
  994. ->where('is_signed_by_hcp', '<>', true);
  995. }
  996. private function appointmentsPendingConfirmationQueryAsDna(){
  997. // WHERE client_id IN (SELECT id FROM client WHERE default_na_pro_id = :me.id) AND status = 'PENDING'
  998. $myId = $this->id;
  999. return Appointment::whereHas('client', function($clientQuery) use ($myId) {
  1000. return $clientQuery->where('default_na_pro_id', $myId);
  1001. })->where('status', 'PENDING');
  1002. }
  1003. private function cancelledAppointmentsPendingAckQueryAsDna(){
  1004. // WHERE client_id IN (SELECT id FROM client WHERE default_na_pro_id = :me.id) AND status = 'CANCELLED' AND is_status_acknowledgement_from_default_na_pending IS TRUE;
  1005. $myId = $this->id;
  1006. return Appointment::whereHas('client', function($clientQuery) use ($myId) {
  1007. return $clientQuery->where('default_na_pro_id', $myId);
  1008. })->where('status', 'CANCELLED')
  1009. ->where('is_status_acknowledgement_from_default_na_pending', true);
  1010. }
  1011. private function reportsPendingAckQueryAsDna(){
  1012. // WHERE client_id IN (SELECT id FROM client WHERE default_na_pro_id = :me.id) AND has_na_pro_signed IS FALSE AND is_entry_error
  1013. $myId = $this->id;
  1014. return IncomingReport::whereHas('client',function($clientQuery) use ($myId) {
  1015. return $clientQuery->where('default_na_pro_id', $myId);
  1016. })->where('has_na_pro_signed', '<>', true)
  1017. ->where('is_entry_error','<>', true);
  1018. }
  1019. private function supplyOrdersPendingMyAckQueryAsDna(){
  1020. // WHERE client_id IN (SELECT id FROM client WHERE default_na_pro_id = :me.id) AND has_na_pro_signed IS FALSE AND is_signed_by_pro IS TRUE AND is_cancelled IS NOT TRUE;
  1021. $myId = $this->id;
  1022. return SupplyOrder::whereHas('client',function($clientQuery) use ($myId) {
  1023. return $clientQuery->where('default_na_pro_id', $myId);
  1024. })->where('has_na_pro_signed', '<>', true)
  1025. ->where('is_signed_by_pro', true)
  1026. ->where('is_cancelled', '<>', true);
  1027. }
  1028. private function supplyOrdersPendingHcpApprovalQueryAsDna(){
  1029. // WHERE client_id IN (SELECT id FROM client WHERE default_na_pro_id = :me.id) AND has_na_pro_signed IS TRUE AND is_signed_by_pro IS NOT TRUE AND is_cancelled IS NOT TRUE;
  1030. $myId = $this->id;
  1031. return SupplyOrder::whereHas('client',function($clientQuery) use ($myId) {
  1032. return $clientQuery->where('default_na_pro_id', $myId);
  1033. })->where('has_na_pro_signed', true)
  1034. ->where('is_signed_by_pro','<>', true)
  1035. ->where('is_cancelled', '<>', true);
  1036. }
  1037. //counts
  1038. public function patientsCountAsDna(){
  1039. return $this->patientsQueryAsDna()->count();
  1040. }
  1041. public function patientsAwaitingMcpVisitCountAsDna(){
  1042. return $this->patientsAwaitingMcpVisitQueryAsDna()->count();
  1043. }
  1044. public function patientsWithoutAppointmentCountAsDna(){
  1045. return $this->patientsWithoutAppointmentQueryAsDna()->count();
  1046. }
  1047. public function encountersPendingMyReviewCountAsDna(){
  1048. return $this->encountersPendingMyReviewQueryAsDna()->count();
  1049. }
  1050. public function encountersInProgressCountAsDna(){
  1051. return $this->encountersInProgressQueryAsDna()->count();
  1052. }
  1053. public function appointmentsPendingConfirmationCountAsDna(){
  1054. return $this->appointmentsPendingConfirmationQueryAsDna()->count();
  1055. }
  1056. public function cancelledAppointmentsPendingAckCountAsDna(){
  1057. return $this->cancelledAppointmentsPendingAckQueryAsDna()->count();
  1058. }
  1059. public function reportsPendingAckCountAsDna(){
  1060. return $this->reportsPendingAckQueryAsDna()->count();
  1061. }
  1062. public function supplyOrdersPendingMyAckCountAsDna(){
  1063. return $this->supplyOrdersPendingMyAckQueryAsDna()->count();
  1064. }
  1065. public function supplyOrdersPendingHcpApprovalCountAsDna(){
  1066. return $this->supplyOrdersPendingHcpApprovalQueryAsDna()->count();
  1067. }
  1068. //records
  1069. private $DNA_RESULTS_PAGE_SIZE = 50;
  1070. public function patientsRecordsAsDna(){
  1071. return $this->patientsQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  1072. }
  1073. public function patientsAwaitingMcpVisitRecordsAsDna(){
  1074. return $this->patientsAwaitingMcpVisitQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  1075. }
  1076. public function patientsWithoutAppointmentRecordsAsDna(){
  1077. return $this->patientsWithoutAppointmentQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  1078. }
  1079. public function encountersPendingMyReviewRecordsAsDna(){
  1080. return $this->encountersPendingMyReviewQueryAsDna()
  1081. ->orderBy('effective_dateest', 'desc')
  1082. ->orderBy('created_at', 'desc')
  1083. ->paginate($this->DNA_RESULTS_PAGE_SIZE);
  1084. }
  1085. public function encountersInProgressRecordsAsDna(){
  1086. return $this->encountersInProgressQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  1087. }
  1088. public function appointmentsPendingConfirmationRecordsAsDna(){
  1089. return $this->appointmentsPendingConfirmationQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  1090. }
  1091. public function cancelledAppointmentsPendingAckRecordsAsDna(){
  1092. return $this->cancelledAppointmentsPendingAckQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  1093. }
  1094. public function reportsPendingAckRecordsAsDna(){
  1095. return $this->reportsPendingAckQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  1096. }
  1097. public function supplyOrdersPendingMyAckRecordsAsDna(){
  1098. return $this->supplyOrdersPendingMyAckQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  1099. }
  1100. public function supplyOrdersPendingHcpApprovalRecordsAsDna(){
  1101. return $this->supplyOrdersPendingHcpApprovalQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  1102. }
  1103. public function measurementsPendingReviewAsDna(){
  1104. //Measurements Pending Review
  1105. // SELECT * FROM measurement WHERE client_id IN (SELECT id FROM client WHERE rmm_pro_id = :me.id)
  1106. // AND has_been_stamped_by_rmm IS FALSE AND is_cellular IS TRUE AND is_cellular_zero IS NOT TRUE AND is_active IS TRUE ORDER BY ts DESC;
  1107. $myId = $this->id;
  1108. return Measurement::whereHas('client',function($clientQuery) use ($myId) {
  1109. return $clientQuery->where('rmm_pro_id', $myId);
  1110. })
  1111. ->where('has_been_stamped_by_rmm', '<>', true)
  1112. ->where('is_cellular', true)
  1113. ->where('is_cellular_zero', '<>', true)
  1114. ->where('is_active', true)
  1115. ->orderBy('ts', 'DESC')
  1116. ->paginate(15);
  1117. }
  1118. public function getProcessingAmountAsDna(){
  1119. $expectedForCm = DB::select(DB::raw("SELECT coalesce(SUM(cm_expected_payment_amount),0) as expected_pay FROM bill WHERE cm_pro_id = :performerProID AND has_cm_been_paid = false AND is_signed_by_cm IS TRUE AND is_cancelled = false"), ['performerProID' => $this->id])[0]->expected_pay;
  1120. $expectedForRme = DB::select(DB::raw("SELECT coalesce(SUM(rme_expected_payment_amount),0) as expected_pay FROM bill WHERE rme_pro_id = :performerProID AND has_rme_been_paid = false AND is_signed_by_rme IS TRUE AND is_cancelled = false"), ['performerProID' => $this->id])[0]->expected_pay;
  1121. $expectedForRmm = DB::select(DB::raw("SELECT coalesce(SUM(rmm_expected_payment_amount),0) as expected_pay FROM bill WHERE rmm_pro_id = :performerProID AND has_rmm_been_paid = false AND is_signed_by_rmm IS TRUE AND is_cancelled = false"), ['performerProID' => $this->id])[0]->expected_pay;
  1122. $expectedForNa = DB::select(DB::raw("SELECT coalesce(SUM(generic_pro_expected_payment_amount),0) as expected_pay FROM bill WHERE generic_pro_id = :performerProID AND has_generic_pro_been_paid = false AND is_signed_by_generic_pro IS TRUE AND is_cancelled = false"), ['performerProID' => $this->id])[0]->expected_pay;
  1123. $totalExpectedAmount = $expectedForCm + $expectedForRme + $expectedForRmm + $expectedForNa;
  1124. return $totalExpectedAmount;
  1125. }
  1126. public function getNextPaymentDateAsDna(){
  1127. $nextPaymentDate = '--';
  1128. //if today is < 15th, next payment is 15th, else nextPayment is
  1129. $today = strtotime(date('Y-m-d'));
  1130. $todayDate = date('j', $today);
  1131. $todayMonth = date('m', $today);
  1132. $todayYear = date('Y', $today);
  1133. if ($todayDate < 15) {
  1134. $nextPaymentDate = new DateTime();
  1135. $nextPaymentDate->setDate($todayYear, $todayMonth, 15);
  1136. $nextPaymentDate = $nextPaymentDate->format('m/d/Y');
  1137. } else {
  1138. $nextPaymentDate = new \DateTime();
  1139. $lastDayOfMonth = date('t', $today);
  1140. $nextPaymentDate->setDate($todayYear, $todayMonth, $lastDayOfMonth);
  1141. $nextPaymentDate = $nextPaymentDate->format('m/d/Y');
  1142. }
  1143. return $nextPaymentDate;
  1144. }
  1145. public function clientSmsesAsDna(){
  1146. $myId = $this->id;
  1147. return ClientSMS::whereHas('client', function($clientQuery) use ($myId){
  1148. return $clientQuery->where('default_na_pro_id', $myId);
  1149. })
  1150. ->orderBy('created_at', 'DESC')
  1151. ->paginate(15);
  1152. }
  1153. public function clientMemosAsDna(){
  1154. $naClientMemos = DB::select(
  1155. DB::raw("
  1156. SELECT c.uid as client_uid, c.name_first, c.name_last,
  1157. cm.uid, cm.content, cm.created_at
  1158. FROM client c join client_memo cm on c.id = cm.client_id
  1159. WHERE
  1160. c.default_na_pro_id = {$this->id}
  1161. ORDER BY cm.created_at DESC
  1162. ")
  1163. );
  1164. return $naClientMemos;
  1165. }
  1166. public function getAppointmentsPendingStatusChangeAckAsDna() {
  1167. $myId = $this->id;
  1168. return Appointment::whereHas('client', function($clientQuery) use ($myId){
  1169. return $clientQuery->where('default_na_pro_id', $myId);
  1170. })
  1171. ->where('is_status_acknowledgement_from_appointment_pro_pending', true)
  1172. ->where('raw_date', '>=', DB::raw('NOW()'))
  1173. ->orderBy('raw_date', 'asc')
  1174. ->get();
  1175. }
  1176. public function getAppointmentsPendingDecisionAckAsDna() {
  1177. $myId = $this->id;
  1178. return Appointment::whereHas('client', function($clientQuery) use ($myId){
  1179. return $clientQuery->where('default_na_pro_id', $myId);
  1180. })
  1181. ->where('is_decision_acknowledgement_from_appointment_pro_pending', true)
  1182. ->where('raw_date', '>=', DB::raw('NOW()'))
  1183. ->orderBy('raw_date', 'asc')
  1184. ->get();
  1185. }
  1186. public function getAppointmentsPendingTimeChangeAckAsDna() {
  1187. $myId = $this->id;
  1188. return Appointment::whereHas('client', function($clientQuery) use ($myId){
  1189. return $clientQuery->where('default_na_pro_id', $myId);
  1190. })
  1191. ->where('is_time_change_acknowledgement_from_appointment_pro_pending', true)
  1192. ->where('raw_date', '>=', DB::raw('NOW()'))
  1193. ->orderBy('raw_date', 'asc')
  1194. ->get();
  1195. }
  1196. function myGenericBills() {
  1197. return Bill::where('bill_service_type', 'GENERIC')
  1198. ->where('generic_pro_id', $this->id)
  1199. ->orderBy('created_at', 'DESC')->get();
  1200. }
  1201. public function myNotesPendingSupervisorPhysicianStamping(){
  1202. $pro = $this;
  1203. return Note::where('is_stamped_by_supervising_physician', false)->where('is_flagged_for_supervising_physician_review', true)->whereHas('hcpCompanyPro', function($qry) use($pro){
  1204. return $qry->whereHas('supervisingPhysicianCompanyPro', function($qr) use($pro){
  1205. return $qr->where('pro_id', $pro->id);
  1206. });
  1207. })->count();
  1208. }
  1209. public function activeClientReviewRequests()
  1210. {
  1211. return $this->hasMany(ClientReviewRequest::class, 'pro_id')->where('is_active', true);
  1212. }
  1213. public function currentMonthClientReviewRequest($clientID){
  1214. return $this->activeClientReviewRequests->where('client_id', $clientID)->where('scoped_month_start_date', date('Y-m-01'))->first();
  1215. }
  1216. //TODO: move to dashboard controller
  1217. public function followupsScheduledForToday() {
  1218. return DB::select(DB::raw("
  1219. SELECT crfu.id AS crfu_id,
  1220. crfu.next_follow_up_reason,
  1221. crfu.next_follow_up_memo,
  1222. pro.name_first as pro_first_name,
  1223. pro.name_last AS pro_last_name,
  1224. c.uid as client_uid,
  1225. (c.name_first || ' ' || c.name_last) as client_name,
  1226. crfu.status AS status
  1227. FROM client_rep_follow_up crfu
  1228. join client c on crfu.id = c.client_rep_follow_up_id
  1229. join pro pro on pro.id = crfu.client_rep_pro_id
  1230. -- WHERE crfu.client_rep_pro_id = :pro_id
  1231. WHERE crfu.next_follow_up_date = :date
  1232. ORDER BY crfu.created_at DESC;
  1233. "), ['date' => date('Y-m-d')]);
  1234. }
  1235. }