Pro.php 51 KB

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