Pro.php 49 KB

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