Pro.php 49 KB

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