Pro.php 66 KB

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