Pro.php 49 KB

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