Pro.php 49 KB

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