HomeController.php 99 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Lib\Backend;
  4. use App\Models\Appointment;
  5. use App\Models\AppointmentConfirmationDecision;
  6. use App\Models\AppSession;
  7. use App\Models\CareMonth;
  8. use App\Models\ClientMemo;
  9. use App\Models\ClientProChange;
  10. use App\Models\ClientSMS;
  11. use App\Models\Facility;
  12. use App\Models\IncomingReport;
  13. use App\Models\MBPayer;
  14. use App\Models\ProProAccess;
  15. use App\Models\SupplyOrder;
  16. use App\Models\Ticket;
  17. use DateTime;
  18. use App\Models\Client;
  19. use App\Models\Bill;
  20. use App\Models\Measurement;
  21. use App\Models\Note;
  22. use App\Models\Pro;
  23. use App\Models\ProTransaction;
  24. use GuzzleHttp\Cookie\CookieJar;
  25. use Illuminate\Http\Request;
  26. use Illuminate\Support\Facades\Cookie;
  27. use Illuminate\Support\Facades\DB;
  28. use Illuminate\Support\Facades\Http;
  29. use App\Models\OutgoingEmailTemplate;
  30. class HomeController extends Controller
  31. {
  32. public function nop() {
  33. return json_encode(["success" => true]);
  34. }
  35. public function confirmSmsAuthToken(Request $request)
  36. {
  37. return view('app/confirm_sms_auth_token');
  38. }
  39. public function setPassword(Request $request)
  40. {
  41. return view('app/set_password');
  42. }
  43. public function setSecurityQuestions(Request $request)
  44. {
  45. return view('app/set_security_questions');
  46. }
  47. public function postConfirmSmsAuthToken(Request $request)
  48. {
  49. try {
  50. $url = config('stag.backendUrl') . '/session/confirmSmsAuthToken';
  51. $data = [
  52. 'cellNumber' => $request->input('cellNumber'),
  53. 'token' => $request->input('token'),
  54. ];
  55. $response = Http::asForm()
  56. ->withHeaders(['sessionKey' => $request->cookie('sessionKey')])
  57. ->post($url, $data)
  58. ->json();
  59. if (!isset($response['success']) || !$response['success']) {
  60. $message = 'API error';
  61. if (isset($response['error'])) {
  62. $message = $response['error'];
  63. if (isset($response['path'])) $message .= ': ' . $response['path'];
  64. } else if (isset($response['message'])) $message = $response['message'];
  65. return redirect('/confirm_sms_auth_token')
  66. ->withInput()
  67. ->with('message', $message);
  68. }
  69. return redirect('/');
  70. } catch (\Exception $e) {
  71. return redirect()->back()
  72. ->with('message', 'Unable to process your request at the moment. Please try again later.')
  73. ->withInput($request->input());
  74. }
  75. }
  76. public function resendSmsAuthToken(Request $request)
  77. {
  78. try {
  79. $url = config('stag.backendUrl') . '/session/resendSmsAuthToken';
  80. $data = [];
  81. $response = Http::asForm()
  82. ->withHeaders(['sessionKey' => $request->cookie('sessionKey')])
  83. ->post($url, $data)
  84. ->json();
  85. if (!isset($response['success']) || !$response['success']) {
  86. $message = 'API error';
  87. if (isset($response['error'])) {
  88. $message = $response['error'];
  89. if (isset($response['path'])) $message .= ': ' . $response['path'];
  90. } else if (isset($response['message'])) $message = $response['message'];
  91. return redirect('/confirm_sms_auth_token')
  92. ->withInput()
  93. ->with('message', $message);
  94. }
  95. return redirect()->back()->withInput()->with('message', "SMS Auth Token sent.");
  96. } catch (\Exception $e) {
  97. return redirect()->back()
  98. ->with('message', 'Unable to process your request at the moment. Please try again later.')
  99. ->withInput($request->input());
  100. }
  101. }
  102. public function postSetPassword(Request $request)
  103. {
  104. try {
  105. $url = config('stag.backendUrl') . '/pro/selfPutPassword';
  106. $data = [
  107. 'newPassword' => $request->input('newPassword'),
  108. 'newPasswordConfirmation' => $request->input('newPasswordConfirmation'),
  109. ];
  110. $response = Http::asForm()
  111. ->withHeaders(['sessionKey' => $request->cookie('sessionKey')])
  112. ->post($url, $data)
  113. ->json();
  114. if (!isset($response['success']) || !$response['success']) {
  115. $message = 'API error';
  116. if (isset($response['error'])) {
  117. $message = $response['error'];
  118. if (isset($response['path'])) $message .= ': ' . $response['path'];
  119. } else if (isset($response['message'])) $message = $response['message'];
  120. return redirect('/set_password')
  121. ->withInput()
  122. ->with('message', $message);
  123. }
  124. return redirect('/');
  125. } catch (\Exception $e) {
  126. return redirect()->back()
  127. ->with('message', 'Unable to process your request at the moment. Please try again later.')
  128. ->withInput($request->input());
  129. }
  130. }
  131. public function postSetSecurityQuestions(Request $request)
  132. {
  133. try {
  134. $url = env('BACKEND_URL', 'http://localhost:8080/api') . '/pro/selfPutSecurityQuestions';
  135. $data = [
  136. 'securityQuestion1' => $request->input('securityQuestion1'),
  137. 'securityAnswer1' => $request->input('securityAnswer1'),
  138. 'securityQuestion2' => $request->input('securityQuestion2'),
  139. 'securityAnswer2' => $request->input('securityAnswer2'),
  140. ];
  141. $response = Http::asForm()
  142. ->withHeaders(['sessionKey' => $request->cookie('sessionKey')])
  143. ->post($url, $data)
  144. ->json();
  145. if (!isset($response['success']) || !$response['success']) {
  146. $message = 'API error';
  147. if (isset($response['error'])) {
  148. $message = $response['error'];
  149. if (isset($response['path'])) $message .= ': ' . $response['path'];
  150. } else if (isset($response['message'])) $message = $response['message'];
  151. return redirect('/set_password')
  152. ->withInput()
  153. ->with('message', $message);
  154. }
  155. return redirect('/');
  156. } catch (\Exception $e) {
  157. return redirect()->back()
  158. ->with('message', 'Unable to process your request at the moment. Please try again later.')
  159. ->withInput($request->input());
  160. }
  161. }
  162. public function dashboard_MCP(Request $request){
  163. $keyNumbers = [];
  164. // Patients // SELECT * FROM client WHERE mcp_pro_id = :me.id;
  165. // New Patients Awaiting Visit // SELECT * FROM client WHERE mcp_pro_id = :me.id AND hasMcpDoneOnboardingVisit != 'YES';
  166. // Notes Pending Signature // SELECT * FROM note WHERE hcp_pro_id = :me.id AND is_cancelled IS NOT TRUE AND has_hcp_signed IS NOT TRUE;
  167. // Notes Pending Billing // SELECT * FROM note WHERE hcp_pro_id = :me.id AND is_cancelled IS NOT TRUE AND has_hcp_signed IS TRUE AND is_billing_marked_done IS FALSE;
  168. // Reports Pending Signature // SELECT * FROM incoming_report WHERE hcp_pro_id = :me.id AND isEntryError IS NOT TRUE AND hasHcpProSigned IS NOT TRUE;
  169. // Patients w/o Appointments // SELECT * FROM client WHERE mcp_pro_id = :me.id AND client.next_mcp_appointment_date < today();
  170. // Patients Overdue for Visit // SELECT * FROM client WHERE mcp_pro_id = :me.id AND client.next_expected_mcp_visit_date < today();
  171. // Cancelled Appts. Pending Review // SELECT * FROM appointment WHERE hcp_pro_id = :me.id AND status = 'REJECTED' AND wasAcknowledgedByAppointmentPro IS NOT TRUE;
  172. // Cancelled Bills Pending Review // SELECT * FROM bill WHERE bill_service_type = 'NOTE' AND is_cancelled IS TRUE AND isCancellationAcknowledged IS FALSE;
  173. // Cancelled Supply Orders Pending Review // SELECT * FROM supply_order WHERE signed_by_pro_id = :me.id AND is_cancelled IS TRUE AND isCancellationAcknowledged IS NOT TRUE;
  174. // ERx & Orders Pending Signature // SELECT * FROM erx WHERE hcp_pro_id = :me.id AND pro_declared_status <> 'CANCELLED' AND hasHcpProSigned IS NOT TRUE;
  175. // Supply Orders Pending Signature // 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;
  176. $performer = $this->performer();
  177. $pro = $performer->pro;
  178. $performerProID = $performer->pro->id;
  179. $keyNumbers = [];
  180. $queryClients = $this->performer()->pro->getAccessibleClientsQuery();
  181. $pendingNotesToSign = Note
  182. ::where(function ($query) use ($performerProID) {
  183. $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_cancelled', false)->where('is_core_note', false);
  184. })
  185. ->orWhere(function ($query) use ($performerProID) {
  186. $query->where('ally_pro_id', $performerProID)->where('is_signed_by_ally', false)->where('is_cancelled', false)->where('is_core_note', false);
  187. })
  188. ->count();
  189. $keyNumbers['pendingNotesToSign'] = $pendingNotesToSign;
  190. // notes pending mcp sign (applicable to dnas only)
  191. $pendingNotesToSignMCP = Note
  192. ::where(function ($query) use ($performerProID) {
  193. $query->where('ally_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_cancelled', false)->where('is_core_note', false);
  194. })
  195. ->count();
  196. $keyNumbers['$pendingNotesToSignMCP'] = $pendingNotesToSignMCP;
  197. $pendingNotesToSignAllySigned = Note::where(function ($query) use ($performerProID) {
  198. $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_signed_by_ally', true)->where('is_cancelled', false)->where('is_core_note', false);;
  199. })->count();
  200. $keyNumbers['pendingNotesToSignAllySigned'] = $pendingNotesToSignAllySigned;
  201. $signedNotesWithoutBills = Note::where(function ($query) use ($performerProID) {
  202. $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', true)->where('is_cancelled', false);
  203. })->whereDoesntHave('bills')->count();
  204. $keyNumbers['signedNotesWithoutBills'] = $signedNotesWithoutBills;
  205. // open tickets
  206. $keyNumbers['numOpenTickets'] = Ticket::where('is_open', true)
  207. ->where(function ($q) use ($performerProID) {
  208. $q->where('assigned_pro_id', $performerProID)
  209. ->orWhere('manager_pro_id', $performerProID)
  210. ->orWhere('ordering_pro_id', $performerProID)
  211. ->orWhere('initiating_pro_id', $performerProID);
  212. })
  213. ->count();
  214. // unacknowledged cancelled bills for authed pro
  215. $keyNumbers['unacknowledgedCancelledBills'] = Bill::where('hcp_pro_id', $performerProID)
  216. ->where('is_cancelled', true)
  217. ->where('is_cancellation_acknowledged', false)
  218. ->count();
  219. // unacknowledged cancelled supply orders for authed pro
  220. $keyNumbers['unacknowledgedCancelledSupplyOrders'] = SupplyOrder::where('signed_by_pro_id', $performerProID)
  221. ->where('is_cancelled', true)
  222. ->where('is_cancellation_acknowledged', false)
  223. ->count();
  224. // unsigned supply orders created by authed pro
  225. $keyNumbers['unsignedSupplyOrders'] = SupplyOrder
  226. ::where('is_cancelled', false)
  227. ->where('is_signed_by_pro', false)
  228. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session WHERE pro_id = ?)', [$performerProID])
  229. ->count();
  230. // patientsHavingBirthdayToday
  231. $queryClients = $this->performer()->pro->getAccessibleClientsQuery();
  232. $keyNumbers['patientsHavingBirthdayToday'] = $queryClients
  233. ->whereRaw('EXTRACT(DAY from dob) = ?', [date('d')])
  234. ->whereRaw('EXTRACT(MONTH from dob) = ?', [date('m')])
  235. ->count();
  236. $reimbursement = [];
  237. $reimbursement["currentBalance"] = $performer->pro->balance;
  238. $reimbursement["nextPaymentDate"] = '--';
  239. $lastPayment = ProTransaction::where('pro_id', $performerProID)->where('plus_or_minus', 'PLUS')->orderBy('created_at', 'DESC')->first();
  240. if ($lastPayment) {
  241. $reimbursement["lastPayment"] = $lastPayment->amount;
  242. $reimbursement["lastPaymentDate"] = $lastPayment->created_at;
  243. } else {
  244. $reimbursement["lastPayment"] = '--';
  245. $reimbursement["lastPaymentDate"] = '--';
  246. }
  247. //if today is < 15th, next payment is 15th, else nextPayment is
  248. $today = strtotime(date('Y-m-d'));
  249. $todayDate = date('j', $today);
  250. $todayMonth = date('m', $today);
  251. $todayYear = date('Y', $today);
  252. if ($todayDate < 15) {
  253. $nextPaymentDate = new DateTime();
  254. $nextPaymentDate->setDate($todayYear, $todayMonth, 15);
  255. $reimbursement['nextPaymentDate'] = $nextPaymentDate->format('m/d/Y');
  256. } else {
  257. $nextPaymentDate = new \DateTime();
  258. $lastDayOfMonth = date('t', $today);
  259. $nextPaymentDate->setDate($todayYear, $todayMonth, $lastDayOfMonth);
  260. $reimbursement['nextPaymentDate'] = $nextPaymentDate->format('m/d/Y');
  261. }
  262. //expectedPay
  263. $expectedForHcp = DB::select(DB::raw("SELECT coalesce(SUM(hcp_expected_payment_amount),0) as expected_pay FROM bill WHERE hcp_pro_id = :performerProID AND has_hcp_been_paid = false AND is_signed_by_hcp IS TRUE AND is_cancelled = false"), ['performerProID' => $performerProID])[0]->expected_pay;
  264. $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' => $performerProID])[0]->expected_pay;
  265. $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' => $performerProID])[0]->expected_pay;
  266. $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' => $performerProID])[0]->expected_pay;
  267. $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' => $performerProID])[0]->expected_pay;
  268. $totalExpectedAmount = $expectedForHcp + $expectedForCm + $expectedForRme + $expectedForRmm + $expectedForNa;
  269. $reimbursement['nextPaymentAmount'] = $totalExpectedAmount;
  270. $milliseconds = strtotime(date('Y-m-d')) . '000';
  271. // bills & claims
  272. $businessNumbers = [];
  273. // Notes with bills to resolve
  274. $businessNumbers['notesWithBillsToResolve'] = Note::where('is_cancelled', '!=', true)
  275. ->where('is_bill_closed', '!=', true)
  276. ->whereRaw('(SELECT count(id) FROM bill WHERE note_id = note.id AND is_cancelled = false AND is_verified = false) > 0')
  277. ->count();
  278. // Notes pending bill closure
  279. $businessNumbers['notesPendingBillingClosure'] = Note::where('is_cancelled', '!=', true)
  280. ->where('is_bill_closed', '!=', true)
  281. ->whereRaw('(SELECT count(id) FROM bill WHERE note_id = note.id AND (is_cancelled = true OR is_verified = true)) = 0')
  282. ->count();
  283. // incoming reports not signed
  284. $incomingReports = IncomingReport::where('hcp_pro_id', $performerProID)
  285. ->where('has_hcp_pro_signed', false)
  286. ->where('is_entry_error', false)
  287. ->orderBy('created_at', 'ASC')
  288. ->get();
  289. // erx, labs & imaging that are not closed
  290. $tickets = Ticket::where('ordering_pro_id', $performerProID)
  291. ->where('is_entry_error', false)
  292. ->where('is_open', true)
  293. ->orderBy('created_at', 'ASC')
  294. ->get();
  295. $supplyOrders = SupplyOrder::where('is_cleared_for_shipment', false)
  296. ->where('is_cancelled', false)
  297. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session where pro_id = ?)', [$performer->pro->id])
  298. ->orderBy('created_at', 'ASC')
  299. ->get();
  300. $numERx = Ticket::where('ordering_pro_id', $performerProID)
  301. ->where('category', 'erx')
  302. ->where('is_entry_error', false)
  303. ->where('is_open', true)
  304. ->count();
  305. $numLabs = Ticket::where('ordering_pro_id', $performerProID)
  306. ->where('category', 'lab')
  307. ->where('is_entry_error', false)
  308. ->where('is_open', true)
  309. ->count();
  310. $numImaging = Ticket::where('ordering_pro_id', $performerProID)
  311. ->where('category', 'imaging')
  312. ->where('is_entry_error', false)
  313. ->where('is_open', true)
  314. ->count();
  315. $numSupplyOrders = SupplyOrder::where('is_cleared_for_shipment', false)
  316. ->where('is_cancelled', false)
  317. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session where pro_id = ?)', [$performer->pro->id])
  318. ->count();
  319. $newMCPAssociations = ClientProChange
  320. ::where('new_pro_id', $performerProID)
  321. ->where('responsibility_type', 'MCP')
  322. ->whereNull('current_client_pro_change_decision_id')
  323. ->get();
  324. $newNAAssociations = ClientProChange
  325. ::where('new_pro_id', $performerProID)
  326. ->where('responsibility_type', 'DEFAULT_NA')
  327. ->whereNull('current_client_pro_change_decision_id')
  328. ->get();
  329. // unstamped client memos
  330. // for mcp
  331. $mcpClientMemos = DB::select(
  332. DB::raw("
  333. SELECT c.uid as client_uid, c.name_first, c.name_last,
  334. cm.uid, cm.content, cm.created_at
  335. FROM client c join client_memo cm on c.id = cm.client_id
  336. WHERE
  337. c.mcp_pro_id = {$performerProID} AND
  338. cm.mcp_stamp_id IS NULL
  339. AND (is_admin_only IS FALSE OR is_admin_only IS NULL)
  340. ORDER BY cm.created_at DESC
  341. OFFSET 0 LIMIT 10
  342. ")
  343. );
  344. $mcpClientMemosCount = DB::select(
  345. DB::raw("
  346. SELECT count(c.uid)
  347. FROM client c join client_memo cm on c.id = cm.client_id
  348. WHERE
  349. c.mcp_pro_id = {$performerProID} AND
  350. cm.mcp_stamp_id IS NULL
  351. AND (is_admin_only IS FALSE OR is_admin_only IS NULL)
  352. ")
  353. );
  354. if($mcpClientMemosCount && count($mcpClientMemosCount)) {
  355. $mcpClientMemosCount = $mcpClientMemosCount[0]->count;
  356. }
  357. // for na
  358. $naClientMemos = DB::select(
  359. DB::raw("
  360. SELECT c.uid as client_uid, c.name_first, c.name_last,
  361. cm.uid, cm.content, cm.created_at
  362. FROM client c join client_memo cm on c.id = cm.client_id
  363. WHERE
  364. c.default_na_pro_id = {$performerProID} AND
  365. cm.default_na_stamp_id IS NULL
  366. ORDER BY cm.created_at DESC
  367. ")
  368. );
  369. $keyNumbers['rmBillsToSign'] = Bill
  370. ::where('is_cancelled', false)
  371. ->where('cm_or_rm', 'RM')
  372. ->where(function ($q) use ($performerProID) {
  373. $q
  374. ->where(function ($q2) use ($performerProID) {
  375. $q2->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false);
  376. })
  377. ->orWhere(function ($q2) use ($performerProID) {
  378. $q2->where('rme_pro_id', $performerProID)->where('is_signed_by_rme', false);
  379. })
  380. ->orWhere(function ($q2) use ($performerProID) {
  381. $q2->where('rmm_pro_id', $performerProID)->where('is_signed_by_rmm', false);
  382. })
  383. ->orWhere(function ($q2) use ($performerProID) {
  384. $q2->where('generic_pro_id', $performerProID)->where('is_signed_by_generic_pro', false);
  385. });
  386. })
  387. ->count();
  388. $count = DB::select(
  389. DB::raw(
  390. "
  391. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  392. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  393. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  394. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  395. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  396. AND (care_month.number_of_days_with_remote_measurements < 16 OR care_month.number_of_days_with_remote_measurements IS NULL)
  397. "
  398. )
  399. );
  400. $keyNumbers['rmPatientsWithLT16MD'] = $count[0]->cnt;
  401. $count = DB::select(
  402. DB::raw(
  403. "
  404. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  405. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  406. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  407. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  408. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  409. AND (care_month.number_of_days_with_remote_measurements >= 16 AND care_month.number_of_days_with_remote_measurements IS NOT NULL)
  410. "
  411. )
  412. );
  413. $keyNumbers['rmPatientsWithGTE16MD'] = $count[0]->cnt;
  414. $count = DB::select(
  415. DB::raw(
  416. "
  417. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  418. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  419. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  420. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  421. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  422. AND (care_month.has_anyone_interacted_with_client_about_rm_outside_note = TRUE AND care_month.has_anyone_interacted_with_client_about_rm_outside_note IS NOT NULL)
  423. "
  424. )
  425. );
  426. $keyNumbers['rmPatientsWithWhomCommDone'] = $count[0]->cnt;
  427. $count = DB::select(
  428. DB::raw(
  429. "
  430. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  431. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  432. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  433. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  434. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  435. AND (care_month.has_anyone_interacted_with_client_about_rm_outside_note = FALSE OR care_month.has_anyone_interacted_with_client_about_rm_outside_note IS NULL)
  436. "
  437. )
  438. );
  439. $keyNumbers['rmPatientsWithWhomCommNotDone'] = $count[0]->cnt;
  440. // num measurements that need stamping
  441. $keyNumbers['measurementsToBeStamped'] = $this->performer()->pro->getUnstampedMeasurementsFromCurrentMonth(true, null, null);
  442. if($performer->pro->pro_type === 'ADMIN') {
  443. // patients without coverage information
  444. $keyNumbers['patientsWithoutCoverageInformation'] = DB::select(DB::raw("
  445. SELECT count(DISTINCT (cl.id)) as cnt
  446. FROM client cl
  447. WHERE cl.shadow_pro_id IS NULL AND cl.latest_client_primary_coverage_id IS NULL -- no coverage record"
  448. ))[0]->cnt;
  449. // patients pending coverage verification
  450. $keyNumbers['patientsPendingCoverageVerification'] = DB::select(DB::raw("
  451. SELECT count(DISTINCT (cl.id)) as cnt
  452. FROM client cl
  453. LEFT JOIN client_primary_coverage cpc ON cl.latest_client_primary_coverage_id = cpc.id
  454. WHERE cl.shadow_pro_id IS NULL
  455. AND (cl.latest_client_primary_coverage_id IS NOT NULL -- coverage exists, but status is null or unknown
  456. AND (
  457. (cpc.plan_type = 'MEDICARE' AND (cpc.is_partbprimary = 'UNKNOWN' OR cpc.is_partbprimary IS NULL))
  458. OR
  459. (cpc.plan_type != 'MEDICARE' AND
  460. (cpc.manual_determination_category = 'UNKNOWN' OR cpc.manual_determination_category IS NULL))
  461. ))"
  462. ))[0]->cnt;
  463. }
  464. $incomingSmsMessagesPendingReply = DB::select("
  465. SELECT cs.* ,c.uid as client_uid, c.name_first as client_name_first, c.name_last as client_name_last FROM client_sms cs LEFT JOIN client c ON c.id = cs.client_id
  466. WHERE cs.is_reply_needed = 'YES' AND c.mcp_pro_id = :mcp_pro_id AND incoming_or_outgoing = 'INCOMING'
  467. AND (cs.created_at > c.last_sms_sent_to_client_at OR c.last_sms_sent_to_client_at IS NULL)
  468. ORDER BY created_at DESC
  469. ", ['mcp_pro_id' => $performer->pro->id]);
  470. $careMonthsWithMeasurementsPendingStamping = CareMonth::select('id')
  471. ->where('mcp_pro_id', $this->performer->pro->id)
  472. ->where('rm_num_measurements_not_stamped_by_mcp', '>', 0)
  473. ->whereNotNull('rm_num_measurements_not_stamped_by_mcp')
  474. ->orderBy('created_at', 'DESC')
  475. ->get()
  476. ->map(function($_x) {
  477. return $_x->id;
  478. })
  479. ->toArray();
  480. $measurementsPendingStamping = Measurement::whereIn('care_month_id', $careMonthsWithMeasurementsPendingStamping)
  481. ->orderBy('created_at', 'DESC')
  482. ->whereNotNull('ts')
  483. ->whereNotIn('label', ['SBP', 'DBP'])
  484. ->where('is_cellular_zero', '<>', true)
  485. ->where('is_active', true)
  486. ->where('has_been_stamped_by_mcp', false)
  487. ->whereNotNull('client_bdt_measurement_id')
  488. ->paginate(15);
  489. return view('app/dashboard-mcp', compact('keyNumbers', 'reimbursement', 'milliseconds',
  490. 'businessNumbers',
  491. 'incomingReports', 'tickets', 'supplyOrders',
  492. 'numERx', 'numLabs', 'numImaging', 'numSupplyOrders',
  493. 'newMCPAssociations', 'newNAAssociations',
  494. 'measurementsPendingStamping', 'careMonthsWithMeasurementsPendingStamping',
  495. 'mcpClientMemos', 'mcpClientMemosCount', 'naClientMemos', 'incomingSmsMessagesPendingReply'));
  496. }
  497. public function dashboard_HCP(Request $request){
  498. //TODO provide hcp specific data. Currently is based on MCP context
  499. $keyNumbers = [];
  500. // Patients // SELECT * FROM client WHERE mcp_pro_id = :me.id;
  501. // New Patients Awaiting Visit // SELECT * FROM client WHERE mcp_pro_id = :me.id AND hasMcpDoneOnboardingVisit != 'YES';
  502. // Notes Pending Signature // SELECT * FROM note WHERE hcp_pro_id = :me.id AND is_cancelled IS NOT TRUE AND has_hcp_signed IS NOT TRUE;
  503. // Notes Pending Billing // SELECT * FROM note WHERE hcp_pro_id = :me.id AND is_cancelled IS NOT TRUE AND has_hcp_signed IS TRUE AND is_billing_marked_done IS FALSE;
  504. // Reports Pending Signature // SELECT * FROM incoming_report WHERE hcp_pro_id = :me.id AND isEntryError IS NOT TRUE AND hasHcpProSigned IS NOT TRUE;
  505. // Patients w/o Appointments // SELECT * FROM client WHERE mcp_pro_id = :me.id AND client.next_mcp_appointment_date < today();
  506. // Patients Overdue for Visit // SELECT * FROM client WHERE mcp_pro_id = :me.id AND client.next_expected_mcp_visit_date < today();
  507. // Cancelled Appts. Pending Review // SELECT * FROM appointment WHERE hcp_pro_id = :me.id AND status = 'REJECTED' AND wasAcknowledgedByAppointmentPro IS NOT TRUE;
  508. // Cancelled Bills Pending Review // SELECT * FROM bill WHERE bill_service_type = 'NOTE' AND is_cancelled IS TRUE AND isCancellationAcknowledged IS FALSE;
  509. // Cancelled Supply Orders Pending Review // SELECT * FROM supply_order WHERE signed_by_pro_id = :me.id AND is_cancelled IS TRUE AND isCancellationAcknowledged IS NOT TRUE;
  510. // ERx & Orders Pending Signature // SELECT * FROM erx WHERE hcp_pro_id = :me.id AND pro_declared_status <> 'CANCELLED' AND hasHcpProSigned IS NOT TRUE;
  511. // Supply Orders Pending Signature // 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;
  512. $performer = $this->performer();
  513. $pro = $performer->pro;
  514. $performerProID = $performer->pro->id;
  515. $keyNumbers = [];
  516. $queryClients = $this->performer()->pro->getAccessibleClientsQuery();
  517. $pendingNotesToSign = Note
  518. ::where(function ($query) use ($performerProID) {
  519. $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_cancelled', false)->where('is_core_note', false);
  520. })
  521. ->orWhere(function ($query) use ($performerProID) {
  522. $query->where('ally_pro_id', $performerProID)->where('is_signed_by_ally', false)->where('is_cancelled', false)->where('is_core_note', false);
  523. })
  524. ->count();
  525. $keyNumbers['pendingNotesToSign'] = $pendingNotesToSign;
  526. // notes pending mcp sign (applicable to dnas only)
  527. $pendingNotesToSignMCP = Note
  528. ::where(function ($query) use ($performerProID) {
  529. $query->where('ally_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_cancelled', false)->where('is_core_note', false);
  530. })
  531. ->count();
  532. $keyNumbers['$pendingNotesToSignMCP'] = $pendingNotesToSignMCP;
  533. $pendingNotesToSignAllySigned = Note::where(function ($query) use ($performerProID) {
  534. $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_signed_by_ally', true)->where('is_cancelled', false)->where('is_core_note', false);;
  535. })->count();
  536. $keyNumbers['pendingNotesToSignAllySigned'] = $pendingNotesToSignAllySigned;
  537. $signedNotesWithoutBills = Note::where(function ($query) use ($performerProID) {
  538. $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', true)->where('is_cancelled', false);
  539. })->whereDoesntHave('bills')->count();
  540. $keyNumbers['signedNotesWithoutBills'] = $signedNotesWithoutBills;
  541. // open tickets
  542. $keyNumbers['numOpenTickets'] = Ticket::where('is_open', true)
  543. ->where(function ($q) use ($performerProID) {
  544. $q->where('assigned_pro_id', $performerProID)
  545. ->orWhere('manager_pro_id', $performerProID)
  546. ->orWhere('ordering_pro_id', $performerProID)
  547. ->orWhere('initiating_pro_id', $performerProID);
  548. })
  549. ->count();
  550. // unacknowledged cancelled bills for authed pro
  551. $keyNumbers['unacknowledgedCancelledBills'] = Bill::where('hcp_pro_id', $performerProID)
  552. ->where('is_cancelled', true)
  553. ->where('is_cancellation_acknowledged', false)
  554. ->count();
  555. // unacknowledged cancelled supply orders for authed pro
  556. $keyNumbers['unacknowledgedCancelledSupplyOrders'] = SupplyOrder::where('signed_by_pro_id', $performerProID)
  557. ->where('is_cancelled', true)
  558. ->where('is_cancellation_acknowledged', false)
  559. ->count();
  560. // unsigned supply orders created by authed pro
  561. $keyNumbers['unsignedSupplyOrders'] = SupplyOrder
  562. ::where('is_cancelled', false)
  563. ->where('is_signed_by_pro', false)
  564. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session WHERE pro_id = ?)', [$performerProID])
  565. ->count();
  566. // patientsHavingBirthdayToday
  567. $queryClients = $this->performer()->pro->getAccessibleClientsQuery();
  568. $keyNumbers['patientsHavingBirthdayToday'] = $queryClients
  569. ->whereRaw('EXTRACT(DAY from dob) = ?', [date('d')])
  570. ->whereRaw('EXTRACT(MONTH from dob) = ?', [date('m')])
  571. ->count();
  572. $reimbursement = [];
  573. $reimbursement["currentBalance"] = $performer->pro->balance;
  574. $reimbursement["nextPaymentDate"] = '--';
  575. $lastPayment = ProTransaction::where('pro_id', $performerProID)->where('plus_or_minus', 'PLUS')->orderBy('created_at', 'DESC')->first();
  576. if ($lastPayment) {
  577. $reimbursement["lastPayment"] = $lastPayment->amount;
  578. $reimbursement["lastPaymentDate"] = $lastPayment->created_at;
  579. } else {
  580. $reimbursement["lastPayment"] = '--';
  581. $reimbursement["lastPaymentDate"] = '--';
  582. }
  583. //if today is < 15th, next payment is 15th, else nextPayment is
  584. $today = strtotime(date('Y-m-d'));
  585. $todayDate = date('j', $today);
  586. $todayMonth = date('m', $today);
  587. $todayYear = date('Y', $today);
  588. if ($todayDate < 15) {
  589. $nextPaymentDate = new DateTime();
  590. $nextPaymentDate->setDate($todayYear, $todayMonth, 15);
  591. $reimbursement['nextPaymentDate'] = $nextPaymentDate->format('m/d/Y');
  592. } else {
  593. $nextPaymentDate = new \DateTime();
  594. $lastDayOfMonth = date('t', $today);
  595. $nextPaymentDate->setDate($todayYear, $todayMonth, $lastDayOfMonth);
  596. $reimbursement['nextPaymentDate'] = $nextPaymentDate->format('m/d/Y');
  597. }
  598. //expectedPay
  599. $expectedForHcp = DB::select(DB::raw("SELECT coalesce(SUM(hcp_expected_payment_amount),0) as expected_pay FROM bill WHERE hcp_pro_id = :performerProID AND has_hcp_been_paid = false AND is_signed_by_hcp IS TRUE AND is_cancelled = false"), ['performerProID' => $performerProID])[0]->expected_pay;
  600. $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' => $performerProID])[0]->expected_pay;
  601. $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' => $performerProID])[0]->expected_pay;
  602. $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' => $performerProID])[0]->expected_pay;
  603. $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' => $performerProID])[0]->expected_pay;
  604. $totalExpectedAmount = $expectedForHcp + $expectedForCm + $expectedForRme + $expectedForRmm + $expectedForNa;
  605. $reimbursement['nextPaymentAmount'] = $totalExpectedAmount;
  606. $milliseconds = strtotime(date('Y-m-d')) . '000';
  607. // bills & claims
  608. $businessNumbers = [];
  609. // Notes with bills to resolve
  610. $businessNumbers['notesWithBillsToResolve'] = Note::where('is_cancelled', '!=', true)
  611. ->where('is_bill_closed', '!=', true)
  612. ->whereRaw('(SELECT count(id) FROM bill WHERE note_id = note.id AND is_cancelled = false AND is_verified = false) > 0')
  613. ->count();
  614. // Notes pending bill closure
  615. $businessNumbers['notesPendingBillingClosure'] = Note::where('is_cancelled', '!=', true)
  616. ->where('is_bill_closed', '!=', true)
  617. ->whereRaw('(SELECT count(id) FROM bill WHERE note_id = note.id AND (is_cancelled = true OR is_verified = true)) = 0')
  618. ->count();
  619. // incoming reports not signed
  620. $incomingReports = IncomingReport::where('hcp_pro_id', $performerProID)
  621. ->where('has_hcp_pro_signed', false)
  622. ->where('is_entry_error', false)
  623. ->orderBy('created_at', 'ASC')
  624. ->get();
  625. // erx, labs & imaging that are not closed
  626. $tickets = Ticket::where('ordering_pro_id', $performerProID)
  627. ->where('is_entry_error', false)
  628. ->where('is_open', true)
  629. ->orderBy('created_at', 'ASC')
  630. ->get();
  631. $supplyOrders = SupplyOrder::where('is_cleared_for_shipment', false)
  632. ->where('is_cancelled', false)
  633. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session where pro_id = ?)', [$performer->pro->id])
  634. ->orderBy('created_at', 'ASC')
  635. ->get();
  636. $numERx = Ticket::where('ordering_pro_id', $performerProID)
  637. ->where('category', 'erx')
  638. ->where('is_entry_error', false)
  639. ->where('is_open', true)
  640. ->count();
  641. $numLabs = Ticket::where('ordering_pro_id', $performerProID)
  642. ->where('category', 'lab')
  643. ->where('is_entry_error', false)
  644. ->where('is_open', true)
  645. ->count();
  646. $numImaging = Ticket::where('ordering_pro_id', $performerProID)
  647. ->where('category', 'imaging')
  648. ->where('is_entry_error', false)
  649. ->where('is_open', true)
  650. ->count();
  651. $numSupplyOrders = SupplyOrder::where('is_cleared_for_shipment', false)
  652. ->where('is_cancelled', false)
  653. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session where pro_id = ?)', [$performer->pro->id])
  654. ->count();
  655. $newMCPAssociations = ClientProChange
  656. ::where('new_pro_id', $performerProID)
  657. ->where('responsibility_type', 'MCP')
  658. ->whereNull('current_client_pro_change_decision_id')
  659. ->get();
  660. $newNAAssociations = ClientProChange
  661. ::where('new_pro_id', $performerProID)
  662. ->where('responsibility_type', 'DEFAULT_NA')
  663. ->whereNull('current_client_pro_change_decision_id')
  664. ->get();
  665. // unstamped client memos
  666. // for mcp
  667. $mcpClientMemos = DB::select(
  668. DB::raw("
  669. SELECT c.uid as client_uid, c.name_first, c.name_last,
  670. cm.uid, cm.content, cm.created_at
  671. FROM client c join client_memo cm on c.id = cm.client_id
  672. WHERE
  673. c.mcp_pro_id = {$performerProID} AND
  674. cm.mcp_stamp_id IS NULL
  675. AND (is_admin_only IS FALSE OR is_admin_only IS NULL)
  676. ORDER BY cm.created_at DESC
  677. OFFSET 0 LIMIT 10
  678. ")
  679. );
  680. $mcpClientMemosCount = DB::select(
  681. DB::raw("
  682. SELECT count(c.uid)
  683. FROM client c join client_memo cm on c.id = cm.client_id
  684. WHERE
  685. c.mcp_pro_id = {$performerProID} AND
  686. cm.mcp_stamp_id IS NULL
  687. AND (is_admin_only IS FALSE OR is_admin_only IS NULL)
  688. ")
  689. );
  690. if($mcpClientMemosCount && count($mcpClientMemosCount)) {
  691. $mcpClientMemosCount = $mcpClientMemosCount[0]->count;
  692. }
  693. // for na
  694. $naClientMemos = DB::select(
  695. DB::raw("
  696. SELECT c.uid as client_uid, c.name_first, c.name_last,
  697. cm.uid, cm.content, cm.created_at
  698. FROM client c join client_memo cm on c.id = cm.client_id
  699. WHERE
  700. c.default_na_pro_id = {$performerProID} AND
  701. cm.default_na_stamp_id IS NULL
  702. ORDER BY cm.created_at DESC
  703. ")
  704. );
  705. $keyNumbers['rmBillsToSign'] = Bill
  706. ::where('is_cancelled', false)
  707. ->where('cm_or_rm', 'RM')
  708. ->where(function ($q) use ($performerProID) {
  709. $q
  710. ->where(function ($q2) use ($performerProID) {
  711. $q2->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false);
  712. })
  713. ->orWhere(function ($q2) use ($performerProID) {
  714. $q2->where('rme_pro_id', $performerProID)->where('is_signed_by_rme', false);
  715. })
  716. ->orWhere(function ($q2) use ($performerProID) {
  717. $q2->where('rmm_pro_id', $performerProID)->where('is_signed_by_rmm', false);
  718. })
  719. ->orWhere(function ($q2) use ($performerProID) {
  720. $q2->where('generic_pro_id', $performerProID)->where('is_signed_by_generic_pro', false);
  721. });
  722. })
  723. ->count();
  724. $count = DB::select(
  725. DB::raw(
  726. "
  727. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  728. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  729. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  730. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  731. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  732. AND (care_month.number_of_days_with_remote_measurements < 16 OR care_month.number_of_days_with_remote_measurements IS NULL)
  733. "
  734. )
  735. );
  736. $keyNumbers['rmPatientsWithLT16MD'] = $count[0]->cnt;
  737. $count = DB::select(
  738. DB::raw(
  739. "
  740. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  741. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  742. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  743. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  744. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  745. AND (care_month.number_of_days_with_remote_measurements >= 16 AND care_month.number_of_days_with_remote_measurements IS NOT NULL)
  746. "
  747. )
  748. );
  749. $keyNumbers['rmPatientsWithGTE16MD'] = $count[0]->cnt;
  750. $count = DB::select(
  751. DB::raw(
  752. "
  753. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  754. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  755. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  756. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  757. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  758. AND (care_month.has_anyone_interacted_with_client_about_rm_outside_note = TRUE AND care_month.has_anyone_interacted_with_client_about_rm_outside_note IS NOT NULL)
  759. "
  760. )
  761. );
  762. $keyNumbers['rmPatientsWithWhomCommDone'] = $count[0]->cnt;
  763. $count = DB::select(
  764. DB::raw(
  765. "
  766. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  767. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  768. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  769. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  770. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  771. AND (care_month.has_anyone_interacted_with_client_about_rm_outside_note = FALSE OR care_month.has_anyone_interacted_with_client_about_rm_outside_note IS NULL)
  772. "
  773. )
  774. );
  775. $keyNumbers['rmPatientsWithWhomCommNotDone'] = $count[0]->cnt;
  776. // num measurements that need stamping
  777. $keyNumbers['measurementsToBeStamped'] = $this->performer()->pro->getUnstampedMeasurementsFromCurrentMonth(true, null, null);
  778. if($performer->pro->pro_type === 'ADMIN') {
  779. // patients without coverage information
  780. $keyNumbers['patientsWithoutCoverageInformation'] = DB::select(DB::raw("
  781. SELECT count(DISTINCT (cl.id)) as cnt
  782. FROM client cl
  783. WHERE cl.shadow_pro_id IS NULL AND cl.latest_client_primary_coverage_id IS NULL -- no coverage record"
  784. ))[0]->cnt;
  785. // patients pending coverage verification
  786. $keyNumbers['patientsPendingCoverageVerification'] = DB::select(DB::raw("
  787. SELECT count(DISTINCT (cl.id)) as cnt
  788. FROM client cl
  789. LEFT JOIN client_primary_coverage cpc ON cl.latest_client_primary_coverage_id = cpc.id
  790. WHERE cl.shadow_pro_id IS NULL
  791. AND (cl.latest_client_primary_coverage_id IS NOT NULL -- coverage exists, but status is null or unknown
  792. AND (
  793. (cpc.plan_type = 'MEDICARE' AND (cpc.is_partbprimary = 'UNKNOWN' OR cpc.is_partbprimary IS NULL))
  794. OR
  795. (cpc.plan_type != 'MEDICARE' AND
  796. (cpc.manual_determination_category = 'UNKNOWN' OR cpc.manual_determination_category IS NULL))
  797. ))"
  798. ))[0]->cnt;
  799. }
  800. $incomingSmsMessagesPendingReply = DB::select("
  801. SELECT cs.* ,c.uid as client_uid, c.name_first as client_name_first, c.name_last as client_name_last FROM client_sms cs LEFT JOIN client c ON c.id = cs.client_id
  802. WHERE cs.is_reply_needed = 'YES' AND c.mcp_pro_id = :mcp_pro_id AND incoming_or_outgoing = 'INCOMING'
  803. AND (cs.created_at > c.last_sms_sent_to_client_at OR c.last_sms_sent_to_client_at IS NULL)
  804. ORDER BY created_at DESC
  805. ", ['mcp_pro_id' => $performer->pro->id]);
  806. $careMonthsWithMeasurementsPendingStamping = CareMonth::select('id')
  807. ->where('mcp_pro_id', $this->performer->pro->id)
  808. ->where('rm_num_measurements_not_stamped_by_mcp', '>', 0)
  809. ->whereNotNull('rm_num_measurements_not_stamped_by_mcp')
  810. ->orderBy('created_at', 'DESC')
  811. ->get()
  812. ->map(function($_x) {
  813. return $_x->id;
  814. })
  815. ->toArray();
  816. $measurementsPendingStamping = Measurement::whereIn('care_month_id', $careMonthsWithMeasurementsPendingStamping)
  817. ->orderBy('created_at', 'DESC')
  818. ->whereNotNull('ts')
  819. ->whereNotIn('label', ['SBP', 'DBP'])
  820. ->where('is_cellular_zero', '<>', true)
  821. ->where('is_active', true)
  822. ->where('has_been_stamped_by_mcp', false)
  823. ->whereNotNull('client_bdt_measurement_id')
  824. ->paginate(15);
  825. return view('app/dashboard-hcp', compact('keyNumbers', 'reimbursement', 'milliseconds',
  826. 'businessNumbers',
  827. 'incomingReports', 'tickets', 'supplyOrders',
  828. 'numERx', 'numLabs', 'numImaging', 'numSupplyOrders',
  829. 'newMCPAssociations', 'newNAAssociations',
  830. 'measurementsPendingStamping', 'careMonthsWithMeasurementsPendingStamping',
  831. 'mcpClientMemos', 'mcpClientMemosCount', 'naClientMemos', 'incomingSmsMessagesPendingReply'));
  832. }
  833. public function dashboard_DNA(Request $request){
  834. $performer = $this->performer();
  835. $pro = $performer->pro;
  836. $performerProID = $performer->pro->id;
  837. $milliseconds = strtotime(date('Y-m-d')) . '000'; //required by the calendar
  838. return view('app/dashboard-dna', compact( 'milliseconds'));
  839. }
  840. public function dashboard_ADMIN(Request $request){
  841. $keyNumbers = [];
  842. // Patients // SELECT * FROM client WHERE mcp_pro_id = :me.id;
  843. // New Patients Awaiting Visit // SELECT * FROM client WHERE mcp_pro_id = :me.id AND hasMcpDoneOnboardingVisit != 'YES';
  844. // Notes Pending Signature // SELECT * FROM note WHERE hcp_pro_id = :me.id AND is_cancelled IS NOT TRUE AND has_hcp_signed IS NOT TRUE;
  845. // Notes Pending Billing // SELECT * FROM note WHERE hcp_pro_id = :me.id AND is_cancelled IS NOT TRUE AND has_hcp_signed IS TRUE AND is_billing_marked_done IS FALSE;
  846. // Reports Pending Signature // SELECT * FROM incoming_report WHERE hcp_pro_id = :me.id AND isEntryError IS NOT TRUE AND hasHcpProSigned IS NOT TRUE;
  847. // Patients w/o Appointments // SELECT * FROM client WHERE mcp_pro_id = :me.id AND client.next_mcp_appointment_date < today();
  848. // Patients Overdue for Visit // SELECT * FROM client WHERE mcp_pro_id = :me.id AND client.next_expected_mcp_visit_date < today();
  849. // Cancelled Appts. Pending Review // SELECT * FROM appointment WHERE hcp_pro_id = :me.id AND status = 'REJECTED' AND wasAcknowledgedByAppointmentPro IS NOT TRUE;
  850. // Cancelled Bills Pending Review // SELECT * FROM bill WHERE bill_service_type = 'NOTE' AND is_cancelled IS TRUE AND isCancellationAcknowledged IS FALSE;
  851. // Cancelled Supply Orders Pending Review // SELECT * FROM supply_order WHERE signed_by_pro_id = :me.id AND is_cancelled IS TRUE AND isCancellationAcknowledged IS NOT TRUE;
  852. // ERx & Orders Pending Signature // SELECT * FROM erx WHERE hcp_pro_id = :me.id AND pro_declared_status <> 'CANCELLED' AND hasHcpProSigned IS NOT TRUE;
  853. // Supply Orders Pending Signature // 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;
  854. $performer = $this->performer();
  855. $pro = $performer->pro;
  856. $performerProID = $performer->pro->id;
  857. $keyNumbers = [];
  858. $queryClients = $this->performer()->pro->getAccessibleClientsQuery();
  859. $pendingNotesToSign = Note
  860. ::where(function ($query) use ($performerProID) {
  861. $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_cancelled', false)->where('is_core_note', false);
  862. })
  863. ->orWhere(function ($query) use ($performerProID) {
  864. $query->where('ally_pro_id', $performerProID)->where('is_signed_by_ally', false)->where('is_cancelled', false)->where('is_core_note', false);
  865. })
  866. ->count();
  867. $keyNumbers['pendingNotesToSign'] = $pendingNotesToSign;
  868. // notes pending mcp sign (applicable to dnas only)
  869. $pendingNotesToSignMCP = Note
  870. ::where(function ($query) use ($performerProID) {
  871. $query->where('ally_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_cancelled', false)->where('is_core_note', false);
  872. })
  873. ->count();
  874. $keyNumbers['$pendingNotesToSignMCP'] = $pendingNotesToSignMCP;
  875. $pendingNotesToSignAllySigned = Note::where(function ($query) use ($performerProID) {
  876. $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_signed_by_ally', true)->where('is_cancelled', false)->where('is_core_note', false);;
  877. })->count();
  878. $keyNumbers['pendingNotesToSignAllySigned'] = $pendingNotesToSignAllySigned;
  879. $signedNotesWithoutBills = Note::where(function ($query) use ($performerProID) {
  880. $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', true)->where('is_cancelled', false);
  881. })->whereDoesntHave('bills')->count();
  882. $keyNumbers['signedNotesWithoutBills'] = $signedNotesWithoutBills;
  883. // open tickets
  884. $keyNumbers['numOpenTickets'] = Ticket::where('is_open', true)
  885. ->where(function ($q) use ($performerProID) {
  886. $q->where('assigned_pro_id', $performerProID)
  887. ->orWhere('manager_pro_id', $performerProID)
  888. ->orWhere('ordering_pro_id', $performerProID)
  889. ->orWhere('initiating_pro_id', $performerProID);
  890. })
  891. ->count();
  892. // unacknowledged cancelled bills for authed pro
  893. $keyNumbers['unacknowledgedCancelledBills'] = Bill::where('hcp_pro_id', $performerProID)
  894. ->where('is_cancelled', true)
  895. ->where('is_cancellation_acknowledged', false)
  896. ->count();
  897. // unacknowledged cancelled supply orders for authed pro
  898. $keyNumbers['unacknowledgedCancelledSupplyOrders'] = SupplyOrder::where('signed_by_pro_id', $performerProID)
  899. ->where('is_cancelled', true)
  900. ->where('is_cancellation_acknowledged', false)
  901. ->count();
  902. // unsigned supply orders created by authed pro
  903. $keyNumbers['unsignedSupplyOrders'] = SupplyOrder
  904. ::where('is_cancelled', false)
  905. ->where('is_signed_by_pro', false)
  906. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session WHERE pro_id = ?)', [$performerProID])
  907. ->count();
  908. // patientsHavingBirthdayToday
  909. $queryClients = $this->performer()->pro->getAccessibleClientsQuery();
  910. $keyNumbers['patientsHavingBirthdayToday'] = $queryClients
  911. ->whereRaw('EXTRACT(DAY from dob) = ?', [date('d')])
  912. ->whereRaw('EXTRACT(MONTH from dob) = ?', [date('m')])
  913. ->count();
  914. $reimbursement = [];
  915. $reimbursement["currentBalance"] = $performer->pro->balance;
  916. $reimbursement["nextPaymentDate"] = '--';
  917. $lastPayment = ProTransaction::where('pro_id', $performerProID)->where('plus_or_minus', 'PLUS')->orderBy('created_at', 'DESC')->first();
  918. if ($lastPayment) {
  919. $reimbursement["lastPayment"] = $lastPayment->amount;
  920. $reimbursement["lastPaymentDate"] = $lastPayment->created_at;
  921. } else {
  922. $reimbursement["lastPayment"] = '--';
  923. $reimbursement["lastPaymentDate"] = '--';
  924. }
  925. //if today is < 15th, next payment is 15th, else nextPayment is
  926. $today = strtotime(date('Y-m-d'));
  927. $todayDate = date('j', $today);
  928. $todayMonth = date('m', $today);
  929. $todayYear = date('Y', $today);
  930. if ($todayDate < 15) {
  931. $nextPaymentDate = new DateTime();
  932. $nextPaymentDate->setDate($todayYear, $todayMonth, 15);
  933. $reimbursement['nextPaymentDate'] = $nextPaymentDate->format('m/d/Y');
  934. } else {
  935. $nextPaymentDate = new \DateTime();
  936. $lastDayOfMonth = date('t', $today);
  937. $nextPaymentDate->setDate($todayYear, $todayMonth, $lastDayOfMonth);
  938. $reimbursement['nextPaymentDate'] = $nextPaymentDate->format('m/d/Y');
  939. }
  940. //expectedPay
  941. $expectedForHcp = DB::select(DB::raw("SELECT coalesce(SUM(hcp_expected_payment_amount),0) as expected_pay FROM bill WHERE hcp_pro_id = :performerProID AND has_hcp_been_paid = false AND is_signed_by_hcp IS TRUE AND is_cancelled = false"), ['performerProID' => $performerProID])[0]->expected_pay;
  942. $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' => $performerProID])[0]->expected_pay;
  943. $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' => $performerProID])[0]->expected_pay;
  944. $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' => $performerProID])[0]->expected_pay;
  945. $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' => $performerProID])[0]->expected_pay;
  946. $totalExpectedAmount = $expectedForHcp + $expectedForCm + $expectedForRme + $expectedForRmm + $expectedForNa;
  947. $reimbursement['nextPaymentAmount'] = $totalExpectedAmount;
  948. $milliseconds = strtotime(date('Y-m-d')) . '000';
  949. // bills & claims
  950. $businessNumbers = [];
  951. // Notes with bills to resolve
  952. $businessNumbers['notesWithBillsToResolve'] = Note::where('is_cancelled', '!=', true)
  953. ->where('is_bill_closed', '!=', true)
  954. ->whereRaw('(SELECT count(id) FROM bill WHERE note_id = note.id AND is_cancelled = false AND is_verified = false) > 0')
  955. ->count();
  956. // Notes pending bill closure
  957. $businessNumbers['notesPendingBillingClosure'] = Note::where('is_cancelled', '!=', true)
  958. ->where('is_bill_closed', '!=', true)
  959. ->whereRaw('(SELECT count(id) FROM bill WHERE note_id = note.id AND (is_cancelled = true OR is_verified = true)) = 0')
  960. ->count();
  961. // incoming reports not signed
  962. $incomingReports = IncomingReport::where('hcp_pro_id', $performerProID)
  963. ->where('has_hcp_pro_signed', false)
  964. ->where('is_entry_error', false)
  965. ->orderBy('created_at', 'ASC')
  966. ->get();
  967. // erx, labs & imaging that are not closed
  968. $tickets = Ticket::where('ordering_pro_id', $performerProID)
  969. ->where('is_entry_error', false)
  970. ->where('is_open', true)
  971. ->orderBy('created_at', 'ASC')
  972. ->get();
  973. $supplyOrders = SupplyOrder::where('is_cleared_for_shipment', false)
  974. ->where('is_cancelled', false)
  975. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session where pro_id = ?)', [$performer->pro->id])
  976. ->orderBy('created_at', 'ASC')
  977. ->get();
  978. $numERx = Ticket::where('ordering_pro_id', $performerProID)
  979. ->where('category', 'erx')
  980. ->where('is_entry_error', false)
  981. ->where('is_open', true)
  982. ->count();
  983. $numLabs = Ticket::where('ordering_pro_id', $performerProID)
  984. ->where('category', 'lab')
  985. ->where('is_entry_error', false)
  986. ->where('is_open', true)
  987. ->count();
  988. $numImaging = Ticket::where('ordering_pro_id', $performerProID)
  989. ->where('category', 'imaging')
  990. ->where('is_entry_error', false)
  991. ->where('is_open', true)
  992. ->count();
  993. $numSupplyOrders = SupplyOrder::where('is_cleared_for_shipment', false)
  994. ->where('is_cancelled', false)
  995. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session where pro_id = ?)', [$performer->pro->id])
  996. ->count();
  997. $newMCPAssociations = [];
  998. if($request->input('mcpas')) {
  999. $newMCPAssociations = ClientProChange
  1000. ::where('new_pro_id', $performerProID)
  1001. ->where('responsibility_type', 'MCP')
  1002. ->whereNull('current_client_pro_change_decision_id')
  1003. ->get();
  1004. }
  1005. else {
  1006. $newMCPAssociations = ClientProChange
  1007. ::where('new_pro_id', $performerProID)
  1008. ->where('responsibility_type', 'MCP')
  1009. ->whereNull('current_client_pro_change_decision_id')
  1010. ->count();
  1011. }
  1012. $newNAAssociations = [];
  1013. if($request->input('naas')) {
  1014. $newNAAssociations = ClientProChange
  1015. ::where('new_pro_id', $performerProID)
  1016. ->where('responsibility_type', 'DEFAULT_NA')
  1017. ->whereNull('current_client_pro_change_decision_id')
  1018. ->get();
  1019. }
  1020. else {
  1021. $newNAAssociations = ClientProChange
  1022. ::where('new_pro_id', $performerProID)
  1023. ->where('responsibility_type', 'DEFAULT_NA')
  1024. ->whereNull('current_client_pro_change_decision_id')
  1025. ->count();
  1026. }
  1027. $proApptUpdates = AppointmentConfirmationDecision
  1028. ::select('appointment_confirmation_decision.uid', 'client.name_first', 'client.name_last', 'appointment.start_time')
  1029. ->rightJoin('appointment', 'appointment.id', '=', 'appointment_confirmation_decision.appointment_id')
  1030. ->rightJoin('client', 'client.id', '=', 'appointment.client_id')
  1031. ->where('appointment_confirmation_decision.was_acknowledged_by_appointment_pro', false)
  1032. ->where('appointment.status', '!=', 'CREATED')
  1033. ->where('appointment.status', '!=', 'COMPLETED')
  1034. ->where('appointment.status', '!=', 'ABANDONED')
  1035. ->where('appointment.pro_id', $performerProID)
  1036. ->where('client.mcp_pro_id', $performerProID)
  1037. ->orderBy('appointment.start_time', 'DESC')
  1038. ->get();
  1039. $naApptUpdates = AppointmentConfirmationDecision
  1040. ::select('appointment_confirmation_decision.uid', 'client.name_first', 'client.name_last', 'pro.name_first as pro_name_first', 'pro.name_last as pro_name_last', 'appointment.start_time')
  1041. ->rightJoin('appointment', 'appointment.id', '=', 'appointment_confirmation_decision.appointment_id')
  1042. ->rightJoin('client', 'client.id', '=', 'appointment.client_id')
  1043. ->rightJoin('pro', 'pro.id', '=', 'appointment.pro_id')
  1044. ->where('appointment_confirmation_decision.was_acknowledged_by_client_default_na', false)
  1045. ->where('appointment.status', '!=', 'CREATED')
  1046. ->where('appointment.status', '!=', 'COMPLETED')
  1047. ->where('appointment.status', '!=', 'ABANDONED')
  1048. ->where('client.default_na_pro_id', $performerProID)
  1049. ->orderBy('appointment.start_time', 'DESC')
  1050. ->get();
  1051. // $naApptUpdates = AppointmentConfirmationDecision
  1052. // ::join('appointment', 'appointment.id', '=', 'appointment_confirmation_decision.appointment_id')
  1053. // ->join('client', 'client.id', '=', 'appointment.client_id')
  1054. // ->where('client.default_na_pro_id', $performerProID)
  1055. // ->where('appointment_confirmation_decision.was_acknowledged_by_client_default_na', false)
  1056. // ->orderBy('appointment.start_time DESC')
  1057. // ->get();
  1058. // unstamped client memos
  1059. // for mcp
  1060. $mcpClientMemos = [];
  1061. if($request->input('mcpcm')) {
  1062. $mcpClientMemos = DB::select(
  1063. DB::raw("
  1064. SELECT c.uid as client_uid, c.name_first, c.name_last,
  1065. cm.uid, cm.content, cm.created_at
  1066. FROM client c join client_memo cm on c.id = cm.client_id
  1067. WHERE
  1068. c.mcp_pro_id = {$performerProID} AND
  1069. cm.mcp_stamp_id IS NULL
  1070. ORDER BY cm.created_at DESC
  1071. ")
  1072. );
  1073. }
  1074. else {
  1075. $mcpClientMemos = DB::select(
  1076. DB::raw("
  1077. SELECT COUNT(cm.id)
  1078. FROM client c join client_memo cm on c.id = cm.client_id
  1079. WHERE
  1080. c.mcp_pro_id = {$performerProID} AND
  1081. cm.mcp_stamp_id IS NULL
  1082. ")
  1083. );
  1084. }
  1085. // for na
  1086. $naClientMemos = [];
  1087. if($request->input('nacm')) {
  1088. $naClientMemos = DB::select(
  1089. DB::raw("
  1090. SELECT c.uid as client_uid, c.name_first, c.name_last,
  1091. cm.uid, cm.content, cm.created_at
  1092. FROM client c join client_memo cm on c.id = cm.client_id
  1093. WHERE
  1094. c.default_na_pro_id = {$performerProID} AND
  1095. cm.default_na_stamp_id IS NULL
  1096. ORDER BY cm.created_at DESC
  1097. ")
  1098. );
  1099. }
  1100. else {
  1101. $naClientMemos = DB::select(
  1102. DB::raw("
  1103. SELECT COUNT(cm.id)
  1104. FROM client c join client_memo cm on c.id = cm.client_id
  1105. WHERE
  1106. c.default_na_pro_id = {$performerProID} AND
  1107. cm.default_na_stamp_id IS NULL
  1108. ")
  1109. );
  1110. }
  1111. $keyNumbers['rmBillsToSign'] = Bill
  1112. ::where('is_cancelled', false)
  1113. ->where('cm_or_rm', 'RM')
  1114. ->where(function ($q) use ($performerProID) {
  1115. $q
  1116. ->where(function ($q2) use ($performerProID) {
  1117. $q2->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false);
  1118. })
  1119. ->orWhere(function ($q2) use ($performerProID) {
  1120. $q2->where('rme_pro_id', $performerProID)->where('is_signed_by_rme', false);
  1121. })
  1122. ->orWhere(function ($q2) use ($performerProID) {
  1123. $q2->where('rmm_pro_id', $performerProID)->where('is_signed_by_rmm', false);
  1124. })
  1125. ->orWhere(function ($q2) use ($performerProID) {
  1126. $q2->where('generic_pro_id', $performerProID)->where('is_signed_by_generic_pro', false);
  1127. });
  1128. })
  1129. ->count();
  1130. $count = DB::select(
  1131. DB::raw(
  1132. "
  1133. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  1134. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  1135. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  1136. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  1137. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  1138. AND (care_month.number_of_days_with_remote_measurements < 16 OR care_month.number_of_days_with_remote_measurements IS NULL)
  1139. "
  1140. )
  1141. );
  1142. $keyNumbers['rmPatientsWithLT16MD'] = $count[0]->cnt;
  1143. $count = DB::select(
  1144. DB::raw(
  1145. "
  1146. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  1147. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  1148. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  1149. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  1150. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  1151. AND (care_month.number_of_days_with_remote_measurements >= 16 AND care_month.number_of_days_with_remote_measurements IS NOT NULL)
  1152. "
  1153. )
  1154. );
  1155. $keyNumbers['rmPatientsWithGTE16MD'] = $count[0]->cnt;
  1156. $count = DB::select(
  1157. DB::raw(
  1158. "
  1159. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  1160. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  1161. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  1162. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  1163. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  1164. AND (care_month.has_anyone_interacted_with_client_about_rm_outside_note = TRUE AND care_month.has_anyone_interacted_with_client_about_rm_outside_note IS NOT NULL)
  1165. "
  1166. )
  1167. );
  1168. $keyNumbers['rmPatientsWithWhomCommDone'] = $count[0]->cnt;
  1169. $count = DB::select(
  1170. DB::raw(
  1171. "
  1172. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  1173. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  1174. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  1175. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  1176. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  1177. AND (care_month.has_anyone_interacted_with_client_about_rm_outside_note = FALSE OR care_month.has_anyone_interacted_with_client_about_rm_outside_note IS NULL)
  1178. "
  1179. )
  1180. );
  1181. $keyNumbers['rmPatientsWithWhomCommNotDone'] = $count[0]->cnt;
  1182. // num measurements that need stamping
  1183. $keyNumbers['measurementsToBeStamped'] = $this->performer()->pro->getUnstampedMeasurementsFromCurrentMonth(true, null, null);
  1184. if($performer->pro->pro_type === 'ADMIN') {
  1185. // patients without coverage information
  1186. $keyNumbers['patientsWithoutCoverageInformation'] = DB::select(DB::raw("
  1187. SELECT count(DISTINCT (cl.id)) as cnt
  1188. FROM client cl
  1189. WHERE cl.shadow_pro_id IS NULL AND cl.latest_client_primary_coverage_id IS NULL -- no coverage record"
  1190. ))[0]->cnt;
  1191. // patients pending coverage verification
  1192. $keyNumbers['patientsPendingCoverageVerification'] = DB::select(DB::raw("
  1193. SELECT count(DISTINCT (cl.id)) as cnt
  1194. FROM client cl
  1195. LEFT JOIN client_primary_coverage cpc ON cl.latest_client_primary_coverage_id = cpc.id
  1196. WHERE cl.shadow_pro_id IS NULL
  1197. AND (cl.latest_client_primary_coverage_id IS NOT NULL -- coverage exists, but status is null or unknown
  1198. AND (
  1199. (cpc.plan_type = 'MEDICARE' AND (cpc.is_partbprimary = 'UNKNOWN' OR cpc.is_partbprimary IS NULL))
  1200. OR
  1201. (cpc.plan_type != 'MEDICARE' AND
  1202. (cpc.manual_determination_category = 'UNKNOWN' OR cpc.manual_determination_category IS NULL))
  1203. ))"
  1204. ))[0]->cnt;
  1205. }
  1206. return view('app/dashboard-admin', compact('keyNumbers', 'reimbursement', 'milliseconds',
  1207. 'businessNumbers',
  1208. 'incomingReports', 'tickets', 'supplyOrders',
  1209. 'numERx', 'numLabs', 'numImaging', 'numSupplyOrders',
  1210. 'newMCPAssociations', 'newNAAssociations',
  1211. 'mcpClientMemos', 'naClientMemos',
  1212. 'proApptUpdates', 'naApptUpdates'));
  1213. }
  1214. public function dashboard(Request $request)
  1215. {
  1216. $performer = $this->performer();
  1217. $pro = $performer->pro;
  1218. if($pro->pro_type === 'ADMIN'){
  1219. return $this->dashboard_ADMIN($request);
  1220. }elseif($pro->is_enrolled_as_mcp && $pro->is_considered_for_mcp_assignment) {
  1221. return $this->dashboard_MCP($request);
  1222. }elseif($pro->is_hcp){
  1223. return $this->dashboard_HCP($request); //TODO for HCP
  1224. }else{
  1225. return $this->dashboard_DNA($request);
  1226. }
  1227. }
  1228. public function dashboardMeasurementsTab(Request $request, $page = 1) {
  1229. $performer = $this->performer();
  1230. $myClientIDs = [];
  1231. if ($performer->pro->pro_type != 'ADMIN') {
  1232. $myClientIDs = $this->getMyClientIds();
  1233. $myClientIDs = implode(", ", $myClientIDs);
  1234. }
  1235. $ifNotAdmin = " AND (
  1236. client.mcp_pro_id = {$performer->pro->id}
  1237. OR client.rmm_pro_id = {$performer->pro->id}
  1238. OR client.rme_pro_id = {$performer->pro->id}
  1239. OR client.physician_pro_id = {$performer->pro->id}
  1240. OR client.id in (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = {$performer->pro->id})
  1241. OR client.id in (SELECT client_id FROM appointment WHERE status NOT IN ('CANCELLED') AND pro_id = {$performer->pro->id})
  1242. )";
  1243. $numMeasurements = DB::select(
  1244. DB::raw(
  1245. "
  1246. SELECT count(measurement.id) as cnt
  1247. FROM measurement
  1248. join client on measurement.client_id = client.id
  1249. WHERE measurement.label NOT IN ('SBP', 'DBP')
  1250. AND (measurement.is_cellular_zero = FALSE or measurement.is_cellular_zero IS NULL)
  1251. AND measurement.is_active IS TRUE
  1252. AND measurement.has_been_stamped_by_mcp IS FALSE
  1253. AND measurement.ts IS NOT NULL
  1254. AND measurement.client_bdt_measurement_id IS NOT NULL
  1255. AND (measurement.status IS NULL OR (measurement.status <> 'ACK' AND measurement.status <> 'INVALID_ACK'))
  1256. AND EXTRACT(MONTH from measurement.created_at) = EXTRACT(MONTH from NOW())
  1257. AND EXTRACT(YEAR from measurement.created_at) = EXTRACT(YEAR from NOW())
  1258. " .
  1259. (
  1260. $performer->pro->pro_type != 'ADMIN' ? $ifNotAdmin : ''
  1261. )
  1262. )
  1263. );
  1264. $numMeasurements = $numMeasurements[0]->cnt;
  1265. $measurements = DB::select(
  1266. DB::raw(
  1267. "
  1268. SELECT measurement.uid as uid,
  1269. care_month.uid as care_month_uid,
  1270. care_month.start_date as care_month_start_date,
  1271. measurement.label,
  1272. measurement.value,
  1273. measurement.sbp_mm_hg,
  1274. measurement.dbp_mm_hg,
  1275. measurement.numeric_value,
  1276. measurement.value_pulse,
  1277. measurement.value_irregular,
  1278. measurement.ts,
  1279. client.id as client_id,
  1280. client.mcp_pro_id,
  1281. client.default_na_pro_id,
  1282. client.rmm_pro_id,
  1283. client.rme_pro_id,
  1284. client.uid as client_uid,
  1285. client.name_last,
  1286. client.name_first,
  1287. care_month.rm_total_time_in_seconds
  1288. FROM measurement
  1289. join client on measurement.client_id = client.id
  1290. join care_month on client.id = care_month.client_id
  1291. WHERE measurement.label NOT IN ('SBP', 'DBP')
  1292. AND (measurement.is_cellular_zero = FALSE or measurement.is_cellular_zero IS NULL)
  1293. AND measurement.is_active IS TRUE
  1294. AND measurement.has_been_stamped_by_mcp IS FALSE
  1295. AND measurement.ts IS NOT NULL
  1296. AND measurement.client_bdt_measurement_id IS NOT NULL
  1297. AND (measurement.status IS NULL OR (measurement.status <> 'ACK' AND measurement.status <> 'INVALID_ACK'))
  1298. AND EXTRACT(MONTH from measurement.created_at) = EXTRACT(MONTH from NOW())
  1299. AND EXTRACT(YEAR from measurement.created_at) = EXTRACT(YEAR from NOW())
  1300. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from NOW())
  1301. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from NOW())
  1302. " .
  1303. (
  1304. $performer->pro->pro_type != 'ADMIN' ? $ifNotAdmin : ''
  1305. )
  1306. ) .
  1307. " ORDER BY measurement.ts DESC LIMIT 20 OFFSET " . (($page - 1) * 20)
  1308. );
  1309. return view('app.dashboard.measurements', compact('numMeasurements', 'measurements', 'page'));
  1310. }
  1311. public function dashboardAppointmentDates(Request $request, $from, $to) {
  1312. $performer = $this->performer();
  1313. $performerProID = $performer->pro->id;
  1314. $isAdmin = ($performer->pro->pro_type === 'ADMIN');
  1315. $results = DB::table('appointment')->select('raw_date')->distinct()->where("start_time", '>=', $from)->where("start_time", '<=', $to.' 23:59:00+00');
  1316. $results = $results->leftJoin('client AS c', 'c.id', '=', 'appointment.id');
  1317. if(!$isAdmin) {
  1318. $results = $results->where(function($query) use ($performerProID){
  1319. return $query->where('appointment.pro_id', $performerProID)
  1320. ->orWhere('c.default_na_pro_id', $performerProID);
  1321. });
  1322. }
  1323. $results = $results->get();
  1324. $dates = [];
  1325. foreach ($results as $result) {
  1326. // $dates[] = strtotime($result->raw_date) . '000';
  1327. $dates[] = $result->raw_date;
  1328. }
  1329. // foreach ($results as $result) {
  1330. // $results->dateYMD = date('Y-m-d', strtotime($result->raw_date));
  1331. // }
  1332. return json_encode($dates);
  1333. }
  1334. public function dashboardAppointments(Request $request, $from, $to) {
  1335. $performer = $this->performer();
  1336. $performerProID = $performer->pro->id;
  1337. $isAdmin = ($performer->pro->pro_type === 'ADMIN');
  1338. // $appointments = Appointment::where("start_time", '>=', $from)->where("start_time", '<=', $to.' 23:59:00+00');
  1339. $appointments = Appointment::where("raw_date", '=', $from);
  1340. if(!$isAdmin) {
  1341. $appointments = $appointments->where(function($q) use ($performerProID) {
  1342. return $q->where("pro_id", $performerProID)
  1343. ->orWhereHas('client', function($clientQuery) use ($performerProID){
  1344. return $clientQuery->where('default_na_pro_id', $performerProID);
  1345. });
  1346. });
  1347. }
  1348. $appointments = $appointments
  1349. // ->whereRaw('status NOT IN (\'CANCELLED\', \'COMPLETED\')')
  1350. ->orderBy('start_time', 'asc')
  1351. ->get();
  1352. foreach ($appointments as $appointment) {
  1353. $date = explode(" ", $appointment->start_time)[0];
  1354. $appointment->milliseconds = strtotime($date) . '000';
  1355. $appointment->newStatus = $appointment->status;
  1356. $appointment->dateYMD = date('Y-m-d', strtotime($appointment->raw_date));
  1357. $appointment->clientName = $appointment->client->displayName();
  1358. $appointment->clientInitials = substr($appointment->client->name_first, 0, 1) . substr($appointment->client->name_last, 0, 1);
  1359. $appointment->isClientShadowOfPro = $appointment->client->shadow_pro_id ? true : false;
  1360. $appointment->proInitials = substr($appointment->pro->name_first, 0, 1) . substr($appointment->pro->name_last, 0, 1);
  1361. $appointment->friendlyStartTime = friendly_time($appointment->raw_start_time);
  1362. $appointment->friendlyEndTime = friendly_time($appointment->raw_end_time);
  1363. $appointment->clientSummary = friendly_date_time($appointment->client->dob, false) . ' (' .
  1364. $appointment->client->age_in_years . ' y.o' .
  1365. ($appointment->client->sex ? ' ' . $appointment->client->sex : '') .
  1366. ')';
  1367. $appointment->clientAge = $appointment->client->age_in_years;
  1368. $appointment->clientSex = $appointment->client->sex;
  1369. $appointment->started = false;
  1370. $appointment->inHowManyHours = date_diff(date_create('now'), date_create($appointment->start_time), false)
  1371. ->format('%R%h h, %i m');
  1372. if ($appointment->inHowManyHours[0] === '-') {
  1373. $appointment->inHowManyHours = substr($appointment->inHowManyHours, 1) . ' ago';
  1374. $appointment->started = true;
  1375. } else {
  1376. $appointment->inHowManyHours = 'Appt. in ' . substr($appointment->inHowManyHours, 1);
  1377. }
  1378. $appointment->clientUid = $appointment->client->uid;
  1379. $appointment->proUid = $appointment->pro->uid;
  1380. $appointment->proName = $appointment->pro->displayName();
  1381. // insurance information
  1382. $appointment->coverage = $appointment->client->getPrimaryCoverageStatus();
  1383. unset($appointment->client);
  1384. unset($appointment->pro);
  1385. unset($appointment->detail_json);
  1386. }
  1387. return json_encode($appointments);
  1388. }
  1389. public function dashboardAppointmentsDisplay(Request $request, $from, $to) {
  1390. $performer = $this->performer();
  1391. $performerProID = $performer->pro->id;
  1392. $isAdmin = ($performer->pro->pro_type === 'ADMIN');
  1393. // $appointments = Appointment::where("start_time", '>=', $from)->where("start_time", '<=', $to.' 23:59:00+00');
  1394. $appointments = Appointment::where("raw_date", '=', $from);
  1395. if(!$isAdmin) {
  1396. $appointments = $appointments->where(function($q) use ($performerProID) {
  1397. return $q->where("pro_id", $performerProID)
  1398. ->orWhereHas('client', function($clientQuery) use ($performerProID){
  1399. return $clientQuery->where('default_na_pro_id', $performerProID);
  1400. });
  1401. });
  1402. }
  1403. $appointments = $appointments
  1404. ->orderBy('start_time', 'asc')
  1405. ->orderBy('end_time', 'asc')
  1406. ->get();
  1407. foreach ($appointments as $appointment) {
  1408. $date = explode(" ", $appointment->start_time)[0];
  1409. $appointment->milliseconds = strtotime($date) . '000';
  1410. $appointment->newStatus = $appointment->status;
  1411. $appointment->dateYMD = date('Y-m-d', strtotime($appointment->raw_date));
  1412. $appointment->clientName = $appointment->client->displayName();
  1413. $appointment->clientInitials = substr($appointment->client->name_first, 0, 1) . substr($appointment->client->name_last, 0, 1);
  1414. $appointment->isClientShadowOfPro = $appointment->client->shadow_pro_id ? true : false;
  1415. $appointment->proInitials = substr($appointment->pro->name_first, 0, 1) . substr($appointment->pro->name_last, 0, 1);
  1416. $appointment->friendlyStartTime = friendly_time($appointment->raw_start_time);
  1417. $appointment->friendlyEndTime = friendly_time($appointment->raw_end_time);
  1418. $appointment->clientSummary = friendly_date_time($appointment->client->dob, false) . ' (' .
  1419. $appointment->client->age_in_years . ' y.o' .
  1420. ($appointment->client->sex ? ' ' . $appointment->client->sex : '') .
  1421. ')';
  1422. $appointment->clientAge = $appointment->client->age_in_years;
  1423. $appointment->clientSex = $appointment->client->sex;
  1424. $appointment->started = false;
  1425. $appointment->inHowManyHours = date_diff(date_create('now'), date_create($appointment->start_time), false)
  1426. ->format('%R%h h, %i m');
  1427. if ($appointment->inHowManyHours[0] === '-') {
  1428. $appointment->inHowManyHours = substr($appointment->inHowManyHours, 1) . ' ago';
  1429. $appointment->started = true;
  1430. } else {
  1431. $appointment->inHowManyHours = 'Appt. in ' . substr($appointment->inHowManyHours, 1);
  1432. }
  1433. $appointment->clientUid = $appointment->client->uid;
  1434. $appointment->proUid = $appointment->pro->uid;
  1435. $appointment->proName = $appointment->pro->displayName();
  1436. // insurance information
  1437. $appointment->coverage = $appointment->client->getPrimaryCoverageStatus();
  1438. // bg color
  1439. $appointment->bgColor = 'bg-white';
  1440. if($appointment->status === 'COMPLETED') {
  1441. $appointment->bgColor = 'event-bg-green';
  1442. }
  1443. else if($appointment->status === 'CANCELLED') {
  1444. $appointment->bgColor = 'event-bg-gray';
  1445. }
  1446. unset($appointment->client);
  1447. unset($appointment->pro);
  1448. unset($appointment->detail_json);
  1449. }
  1450. return view('app.mcp.dashboard.appointments-list', compact('appointments', 'from', 'to'));
  1451. }
  1452. public function dashboardMeasurements(Request $request, $filter) {
  1453. $measurements = $this->performer()->pro->getMeasurements($filter === 'NEED_ACK');
  1454. return json_encode($measurements);
  1455. }
  1456. public function patients(Request $request, $filter = '')
  1457. {
  1458. $performer = $this->performer();
  1459. $query = $performer->pro->getAccessibleClientsQuery();
  1460. $q = trim($request->input('q'));
  1461. if(!empty($q)) {
  1462. $query = $query->where(function ($query) use ($q) {
  1463. $query->where('name_first', 'ILIKE', "%$q%")
  1464. ->orWhere('name_last', 'ILIKE', "%$q%")
  1465. ->orWhere('email_address', 'ILIKE', "%$q%")
  1466. ->orWhere('tags', 'ILIKE', "%$q%");
  1467. });
  1468. }
  1469. switch ($filter) {
  1470. case 'not-yet-seen':
  1471. $query = $query
  1472. ->where(function ($query) use ($performer) {
  1473. $query
  1474. ->where(function ($query) use ($performer) { // own patient and primary OB visit pending
  1475. $query->where('mcp_pro_id', $performer->pro->id)
  1476. ->where('has_mcp_done_onboarding_visit', '<>', 'YES');
  1477. })
  1478. ->orWhere(function ($query) use ($performer) { // mcp of any client program and program OB pending
  1479. $query->select(DB::raw('COUNT(id)'))
  1480. ->from('client_program')
  1481. ->whereColumn('client_id', 'client.id')
  1482. ->where('mcp_pro_id', $performer->pro->id)
  1483. ->where('has_mcp_done_onboarding_visit', '<>', 'YES');
  1484. }, '>=', 1);
  1485. });
  1486. break;
  1487. case 'having-birthday-today':
  1488. $query = $query
  1489. ->whereRaw('EXTRACT(DAY from dob) = ?', [date('d')])
  1490. ->whereRaw('EXTRACT(MONTH from dob) = ?', [date('m')]);
  1491. break;
  1492. // more cases can be added as needed
  1493. default:
  1494. break;
  1495. }
  1496. $patients = $query->orderBy('created_at', 'desc')->paginate(50);
  1497. // patient acquisition chart (admin only)
  1498. $patientAcquisitionData = null;
  1499. if($performer->pro->pro_type === 'ADMIN') {
  1500. $startDate = date_sub(date_create(), date_interval_create_from_date_string("1 month"));
  1501. $startDate = date_format($startDate, "Y-m-d");
  1502. $patientAcquisitionData = DB::select(DB::raw(
  1503. "SELECT count(id) as count, DATE(created_at at time zone 'utc' at time zone 'est') as date " .
  1504. "FROM client " .
  1505. "WHERE shadow_pro_id IS NULL " .
  1506. "GROUP BY DATE(created_at at time zone 'utc' at time zone 'est') " .
  1507. "ORDER BY DATE(created_at at time zone 'utc' at time zone 'est') DESC " .
  1508. "LIMIT 30"));
  1509. }
  1510. return view('app/patients', compact('patients', 'filter', 'patientAcquisitionData'));
  1511. }
  1512. public function patientsSuggest(Request $request)
  1513. {
  1514. $pro = $this->pro;
  1515. $term = $request->input('term') ? trim($request->input('term')) : '';
  1516. $originalTerm = $term;
  1517. if (empty($term)) return '';
  1518. // if multiple words in query, check for all (max 2)
  1519. $term2 = '';
  1520. if(strpos($term, ' ') !== FALSE) {
  1521. $terms = explode(' ', $term);
  1522. $term = trim($terms[0]);
  1523. $term2 = trim($terms[1]);
  1524. }
  1525. $phoneNumberTerm = preg_replace("/[^0-9]/", "", $originalTerm );
  1526. if($phoneNumberTerm == ""){ //to avoid search with blank string
  1527. $phoneNumberTerm = $term;
  1528. }
  1529. $clientQuery= Client::whereNull('shadow_pro_id')
  1530. ->where(function ($q) use ($term, $phoneNumberTerm) {
  1531. $q->where('name_first', 'ILIKE', '%' . $term . '%')
  1532. ->orWhere('name_last', 'ILIKE', '%' . $term . '%')
  1533. ->orWhere('cell_number', 'ILIKE', '%' . $phoneNumberTerm . '%')
  1534. ->orWhere('phone_home', 'ILIKE', '%' . $phoneNumberTerm . '%');
  1535. });
  1536. if(!empty($term2)) {
  1537. $clientQuery = $clientQuery->where(function ($q) use ($term2, $phoneNumberTerm) {
  1538. $q->where('name_first', 'ILIKE', '%' . $term2 . '%')
  1539. ->orWhere('name_last', 'ILIKE', '%' . $term2 . '%')
  1540. ->orWhere('cell_number', 'ILIKE', '%' . $phoneNumberTerm . '%')
  1541. ->orWhere('phone_home', 'ILIKE', '%' . $phoneNumberTerm . '%');
  1542. });
  1543. }
  1544. if(!($pro->pro_type === 'ADMIN' && $pro->can_see_any_client_via_search)) {
  1545. $clientQuery->where(function ($q) use ($pro) {
  1546. if($pro->pro_type === 'ADMIN' || $pro->is_enrolled_as_mcp) {
  1547. $q->whereIn('id', $pro->getMyClientIds(true))->orWhereNull('mcp_pro_id');
  1548. }
  1549. else {
  1550. $q->whereIn('id', $pro->getMyClientIds(true));
  1551. }
  1552. });
  1553. }
  1554. $clients = $clientQuery->get();
  1555. return view('app/patient-suggest', compact('clients'));
  1556. }
  1557. public function pharmacySuggest(Request $request)
  1558. {
  1559. $term = $request->input('term') ? trim($request->input('term')) : '';
  1560. if (empty($term)) return '';
  1561. $term = strtolower($term);
  1562. $pharmacies = Facility::where('facility_type', 'Pharmacy')
  1563. ->where(function ($q) use ($term) {
  1564. $q->orWhereRaw('LOWER(name::text) LIKE ?', ['%' . $term . '%'])
  1565. ->orWhereRaw('LOWER(address_line1::text) LIKE ?', ['%' . $term . '%'])
  1566. ->orWhereRaw('LOWER(address_line2::text) LIKE ?', ['%' . $term . '%'])
  1567. ->orWhereRaw('LOWER(address_city::text) LIKE ?', ['%' . $term . '%'])
  1568. ->orWhereRaw('LOWER(address_state::text) LIKE ?', ['%' . $term . '%'])
  1569. ->orWhereRaw('LOWER(phone::text) LIKE ?', ['%' . $term . '%'])
  1570. ->orWhereRaw('LOWER(address_zip::text) LIKE ?', ['%' . $term . '%']);
  1571. });
  1572. if($request->input('city')) {
  1573. $pharmacies = $pharmacies->whereRaw('LOWER(address_city::text) LIKE ?', ['%' . strtolower($request->input('city')) . '%']);
  1574. }
  1575. if($request->input('state')) {
  1576. $pharmacies = $pharmacies->whereRaw('LOWER(address_state::text) LIKE ?', ['%' . strtolower($request->input('state')) . '%']);
  1577. }
  1578. if($request->input('zip')) {
  1579. $pharmacies = $pharmacies->whereRaw('LOWER(address_zip::text) LIKE ?', ['%' . strtolower($request->input('zip')) . '%']);
  1580. }
  1581. $pharmacies = $pharmacies
  1582. ->orderBy('name', 'asc')
  1583. ->orderBy('address_line1', 'asc')
  1584. ->orderBy('address_city', 'asc')
  1585. ->orderBy('address_state', 'asc')
  1586. ->get();
  1587. return view('app/pharmacy-suggest', compact('pharmacies'));
  1588. }
  1589. public function facilitySuggestJSON(Request $request)
  1590. {
  1591. $term = $request->input('term') ? trim($request->input('term')) : '';
  1592. if (empty($term)) return '';
  1593. $terms = explode(' ', $term);
  1594. $terms = array_filter($terms, function($_x) {
  1595. return !!trim($_x);
  1596. });
  1597. $whereCondition = [];
  1598. $whereParams = [];
  1599. for ($i = 0; $i < count($terms); $i++) {
  1600. $whereCondition[] = "(name ILIKE :term{$i} OR address_city ILIKE :term{$i} OR address_state ILIKE :term{$i} OR address_zip ILIKE :term{$i})";
  1601. $whereParams["term{$i}"] = '%' . $terms[$i] . '%';
  1602. }
  1603. $whereCondition = implode(" AND ", $whereCondition);
  1604. $matches = DB::select(
  1605. "SELECT (name || ' ' || address_city || ' ' || address_state || ' ' || address_zip) as text,
  1606. address_line1 as text2,
  1607. name, address_city as city, address_state as state, address_zip as zip, phone, fax FROM facility
  1608. WHERE {$whereCondition} ORDER BY name", $whereParams);
  1609. return json_encode([
  1610. "success" => true,
  1611. "data" => $matches
  1612. ]);
  1613. }
  1614. public function proSuggest(Request $request) {
  1615. $term = $request->input('term') ? trim($request->input('term')) : '';
  1616. if (empty($term)) return '';
  1617. $term = strtolower($term);
  1618. // if multiple words in query, check for all (max 2)
  1619. $term2 = '';
  1620. if(strpos($term, ' ') !== FALSE) {
  1621. $terms = explode(' ', $term);
  1622. $term = trim($terms[0]);
  1623. $term2 = trim($terms[1]);
  1624. }
  1625. $pros = Pro::where(function ($q) use ($term) {
  1626. $q->orWhereRaw('LOWER(name_first::text) LIKE ?', ['%' . $term . '%'])
  1627. ->orWhereRaw('LOWER(name_last::text) LIKE ?', ['%' . $term . '%'])
  1628. ->orWhereRaw('cell_number LIKE ?', ['%' . $term . '%']);
  1629. });
  1630. if(!empty($term2)) {
  1631. $pros = $pros->where(function ($q) use ($term2) {
  1632. $q->orWhereRaw('LOWER(name_first::text) LIKE ?', ['%' . $term2 . '%'])
  1633. ->orWhereRaw('LOWER(name_last::text) LIKE ?', ['%' . $term2 . '%'])
  1634. ->orWhereRaw('cell_number LIKE ?', ['%' . $term2 . '%']);
  1635. });
  1636. }
  1637. $type = $request->input('type') ? trim($request->input('type')) : '';
  1638. if(!!$type) {
  1639. switch(strtolower($type)) {
  1640. case 'hcp':
  1641. $pros->where('is_hcp', true);
  1642. break;
  1643. case 'default-na': // TODO: fix condition for NA
  1644. $pros->where('is_hcp', false)->where('pro_type', '!=', 'ADMIN');
  1645. break;
  1646. case 'admin':
  1647. $pros->where('pro_type', 'ADMIN');
  1648. break;
  1649. case 'non-admin':
  1650. $pros->where('pro_type', '!=', 'ADMIN');
  1651. break;
  1652. }
  1653. }
  1654. if($this->performer->pro && $this->performer->pro->pro_type != 'ADMIN'){
  1655. $accessiblePros = ProProAccess::where('owner_pro_id', $this->performer->pro->id);
  1656. $accessibleProIds = [];
  1657. foreach($accessiblePros as $accessiblePro){
  1658. $accessibleProIds[] = $accessiblePro->id;
  1659. }
  1660. $accessibleProIds[] = $this->performer->pro->id;
  1661. // for dna, add pros accessible via pro teams
  1662. if($this->performer->pro->isDefaultNA()) {
  1663. $teams = $this->performer->pro->teamsWhereAssistant;
  1664. foreach ($teams as $team) {
  1665. if(!in_array($team->mcp_pro_id, $accessibleProIds)) {
  1666. $accessibleProIds[] = $team->mcp_pro_id;
  1667. }
  1668. }
  1669. }
  1670. $teams = $this->performer->pro->teamsWhereMcp;
  1671. foreach ($teams as $team) {
  1672. if(!in_array($team->assistant_pro_id, $accessibleProIds)) {
  1673. $accessibleProIds[] = $team->assistant_pro_id;
  1674. }
  1675. }
  1676. $pros->whereIn('id', $accessibleProIds);
  1677. }
  1678. $suggestedPros = $pros->orderBy('name_last')->orderBy('name_first')->get();
  1679. // for calendar select2
  1680. if($request->input('json')) {
  1681. $onlyProsThatCanAccessClientUid = $request->get('canAccessClientUid');
  1682. $jsonPros = $suggestedPros->map(function($_pro) use($onlyProsThatCanAccessClientUid) {
  1683. if($onlyProsThatCanAccessClientUid){
  1684. if(!$_pro->canAccess($onlyProsThatCanAccessClientUid)) return false;
  1685. }
  1686. return [
  1687. "uid" => $_pro->uid,
  1688. "id" => $_pro->id,
  1689. "text" => $_pro->displayName(),
  1690. "initials" => $_pro->initials(),
  1691. ];
  1692. });
  1693. return json_encode([
  1694. "results" => $jsonPros
  1695. ]);
  1696. }
  1697. return view('app/pro-suggest', compact('suggestedPros'));
  1698. }
  1699. public function canAccessPatient(Request $request, $uid) {
  1700. return json_encode([
  1701. "success" => true,
  1702. "data" => $this->performer->pro->canAccess($uid)
  1703. ]);
  1704. }
  1705. public function proDisplayName(Request $request, Pro $pro) {
  1706. return $pro ? $pro->displayName() : '';
  1707. }
  1708. public function unmappedSMS(Request $request, $filter = '')
  1709. {
  1710. $proID = $this->performer()->pro->id;
  1711. if ($this->performer()->pro->pro_type === 'ADMIN') {
  1712. $query = Client::where('id', '>', 0);
  1713. } else {
  1714. $query = Client::where(function ($q) use ($proID) {
  1715. $q->where('mcp_pro_id', $proID)
  1716. ->orWhere('cm_pro_id', $proID)
  1717. ->orWhere('rmm_pro_id', $proID)
  1718. ->orWhere('rme_pro_id', $proID)
  1719. ->orWhereRaw('id IN (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = ?)', [$proID]);
  1720. });
  1721. }
  1722. $patients = $query->orderBy('name_last', 'asc')->orderBy('name_first', 'asc')->get();
  1723. $unmappedSMS = ClientSMS::where('client_id', null)->where('incoming_or_outgoing', 'INCOMING')->paginate(20);
  1724. return view('app/unmapped-sms', compact('unmappedSMS', 'patients'));
  1725. }
  1726. public function newPatient(Request $request)
  1727. {
  1728. $mbPayers = MBPayer::all();
  1729. return view('app/new-patient', compact('mbPayers'));
  1730. }
  1731. public function newNonMcnPatient(Request $request)
  1732. {
  1733. $mbPayers = MBPayer::all();
  1734. return view('app/new-non-mcn-patient', compact('mbPayers'));
  1735. }
  1736. public function mc(Request $request, $fragment = "")
  1737. {
  1738. $page = "/";
  1739. if ($fragment) {
  1740. $page = '/' . $fragment;
  1741. }
  1742. return view('app/mc', compact('page'));
  1743. }
  1744. public function blank(Request $request)
  1745. {
  1746. return view('app/blank');
  1747. }
  1748. public function noteTemplateSet(Request $request, $section, $template)
  1749. {
  1750. return view('app/patient/note/_template', [
  1751. "sectionInternalName" => $section,
  1752. "templateName" => $template
  1753. ]);
  1754. }
  1755. public function noteExamTemplateSet(Request $request, $exam, $template)
  1756. {
  1757. return view('app/patient/note/_template-exam', [
  1758. "exam" => $exam,
  1759. "sectionInternalName" => 'exam-' . $exam . '-detail',
  1760. "templateName" => $template
  1761. ]);
  1762. }
  1763. public function logInAs(Request $request)
  1764. {
  1765. if($this->pro->pro_type != 'ADMIN'){
  1766. return redirect()->to(route('dashboard'));
  1767. }
  1768. // dummy condition to get the chain-ability going
  1769. $pros = Pro::where('id', '>', 0);
  1770. if($request->input('q')) {
  1771. $nameQuery = '%' . $request->input('q') . '%';
  1772. $pros = $pros->where(function ($query) use ($nameQuery) {
  1773. $query->where('name_first', 'ILIKE', $nameQuery)
  1774. ->orWhere('name_last', 'ILIKE', $nameQuery)
  1775. ->orWhere('email_address', 'ILIKE', $nameQuery)
  1776. ->orWhere('cell_number', 'ILIKE', $nameQuery);
  1777. });
  1778. }
  1779. if($request->input('sort') && $request->input('dir')) {
  1780. $pros = $pros->orderBy($request->input('sort'), $request->input('dir'));
  1781. }
  1782. else {
  1783. $pros = $pros->orderBy('name_last', 'asc');
  1784. }
  1785. $pros = $pros->paginate(20);
  1786. return view('app/log-in-as', ['logInAsPros' => $pros]);
  1787. }
  1788. public function processLogInAs(Request $request)
  1789. {
  1790. $api = new Backend();
  1791. try {
  1792. $apiResponse = $api->post('session/proLogInAs', [
  1793. 'proUid' => $request->post('proUid')
  1794. ],
  1795. [
  1796. 'sessionKey'=>$this->performer()->session_key
  1797. ]);
  1798. $data = json_decode($apiResponse->getContents());
  1799. if (!property_exists($data, 'success') || !$data->success) {
  1800. return redirect()->to(route('log-in-as'))->with('message', $data->message)
  1801. ->withInput($request->input());
  1802. }
  1803. Cookie::queue('sessionKey', $data->data->sessionKey);
  1804. return redirect('/mc');
  1805. } catch (\Exception $e) {
  1806. return redirect()->to(route('log-in-as'))
  1807. ->with('message', 'Unable to process your request at the moment. Please try again later.')
  1808. ->withInput($request->input());
  1809. }
  1810. }
  1811. public function backToAdminPro(Request $request){
  1812. $adminPerformerId = $this->performer->logged_in_as_pro_from_admin_pro_app_session_id;
  1813. $adminPerformer = AppSession::where('id', $adminPerformerId)->first();
  1814. $url = "/session/pro_log_in_with_session_key/".$adminPerformer->session_key;
  1815. $api = new Backend();
  1816. try {
  1817. $apiResponse = $api->post($url, []);
  1818. $data = json_decode($apiResponse->getContents());
  1819. if (!property_exists($data, 'success') || !$data->success) {
  1820. return redirect()->to(route('logout'));
  1821. }
  1822. Cookie::queue('sessionKey', $data->data->sessionKey);
  1823. return redirect(route('dashboard'));
  1824. } catch (\Exception $e) {
  1825. return redirect(route('dashboard'));
  1826. }
  1827. }
  1828. public function getTicket(Request $request, Ticket $ticket) {
  1829. $ticket->data = json_decode($ticket->data);
  1830. // $ticket->created_at = friendly_date_time($ticket->created_at);
  1831. $ticket->assignedPro;
  1832. $ticket->managerPro;
  1833. $ticket->orderingPro;
  1834. $ticket->initiatingPro;
  1835. return json_encode($ticket);
  1836. }
  1837. public function genericBill(Request $request, $entityType, $entityUid) {
  1838. $patient = null;
  1839. if ($entityType && $entityUid) {
  1840. try {
  1841. $entityClass = "\\App\\Models\\" . $entityType;
  1842. $entity = $entityClass::where('uid', $entityUid)->first();
  1843. if ($entity->client) {
  1844. $patient = $entity->client;
  1845. }
  1846. } catch (\Exception $e) {
  1847. }
  1848. }
  1849. return view('app.generic-bills.inline', ['class' => 'p-3 border-top mt-3', 'entityType' => $entityType, 'entityUid' => $entityUid, 'patient' => $patient]);
  1850. }
  1851. public function outgoingEmailTemplates(Request $request){
  1852. $templates = OutgoingEmailTemplate::where('is_active', true)->orderBy('default_subject_tpl', 'ASC')->get();
  1853. return $this->pass($templates);
  1854. }
  1855. }