HomeController.php 97 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075
  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 = ClientProChange
  998. ::where('new_pro_id', $performerProID)
  999. ->where('responsibility_type', 'MCP')
  1000. ->whereNull('current_client_pro_change_decision_id')
  1001. ->get();
  1002. $newNAAssociations = ClientProChange
  1003. ::where('new_pro_id', $performerProID)
  1004. ->where('responsibility_type', 'DEFAULT_NA')
  1005. ->whereNull('current_client_pro_change_decision_id')
  1006. ->get();
  1007. $proApptUpdates = AppointmentConfirmationDecision
  1008. ::select('appointment_confirmation_decision.uid', 'client.name_first', 'client.name_last', 'appointment.start_time')
  1009. ->rightJoin('appointment', 'appointment.id', '=', 'appointment_confirmation_decision.appointment_id')
  1010. ->rightJoin('client', 'client.id', '=', 'appointment.client_id')
  1011. ->where('appointment_confirmation_decision.was_acknowledged_by_appointment_pro', false)
  1012. ->where('appointment.status', '!=', 'CREATED')
  1013. ->where('appointment.status', '!=', 'COMPLETED')
  1014. ->where('appointment.status', '!=', 'ABANDONED')
  1015. ->where('appointment.pro_id', $performerProID)
  1016. ->where('client.mcp_pro_id', $performerProID)
  1017. ->orderBy('appointment.start_time', 'DESC')
  1018. ->get();
  1019. $naApptUpdates = AppointmentConfirmationDecision
  1020. ::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')
  1021. ->rightJoin('appointment', 'appointment.id', '=', 'appointment_confirmation_decision.appointment_id')
  1022. ->rightJoin('client', 'client.id', '=', 'appointment.client_id')
  1023. ->rightJoin('pro', 'pro.id', '=', 'appointment.pro_id')
  1024. ->where('appointment_confirmation_decision.was_acknowledged_by_client_default_na', false)
  1025. ->where('appointment.status', '!=', 'CREATED')
  1026. ->where('appointment.status', '!=', 'COMPLETED')
  1027. ->where('appointment.status', '!=', 'ABANDONED')
  1028. ->where('client.default_na_pro_id', $performerProID)
  1029. ->orderBy('appointment.start_time', 'DESC')
  1030. ->get();
  1031. // $naApptUpdates = AppointmentConfirmationDecision
  1032. // ::join('appointment', 'appointment.id', '=', 'appointment_confirmation_decision.appointment_id')
  1033. // ->join('client', 'client.id', '=', 'appointment.client_id')
  1034. // ->where('client.default_na_pro_id', $performerProID)
  1035. // ->where('appointment_confirmation_decision.was_acknowledged_by_client_default_na', false)
  1036. // ->orderBy('appointment.start_time DESC')
  1037. // ->get();
  1038. // unstamped client memos
  1039. // for mcp
  1040. $mcpClientMemos = DB::select(
  1041. DB::raw("
  1042. SELECT c.uid as client_uid, c.name_first, c.name_last,
  1043. cm.uid, cm.content, cm.created_at
  1044. FROM client c join client_memo cm on c.id = cm.client_id
  1045. WHERE
  1046. c.mcp_pro_id = {$performerProID} AND
  1047. cm.mcp_stamp_id IS NULL
  1048. ORDER BY cm.created_at DESC
  1049. ")
  1050. );
  1051. // for na
  1052. $naClientMemos = DB::select(
  1053. DB::raw("
  1054. SELECT c.uid as client_uid, c.name_first, c.name_last,
  1055. cm.uid, cm.content, cm.created_at
  1056. FROM client c join client_memo cm on c.id = cm.client_id
  1057. WHERE
  1058. c.default_na_pro_id = {$performerProID} AND
  1059. cm.default_na_stamp_id IS NULL
  1060. ORDER BY cm.created_at DESC
  1061. ")
  1062. );
  1063. $keyNumbers['rmBillsToSign'] = Bill
  1064. ::where('is_cancelled', false)
  1065. ->where('cm_or_rm', 'RM')
  1066. ->where(function ($q) use ($performerProID) {
  1067. $q
  1068. ->where(function ($q2) use ($performerProID) {
  1069. $q2->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false);
  1070. })
  1071. ->orWhere(function ($q2) use ($performerProID) {
  1072. $q2->where('rme_pro_id', $performerProID)->where('is_signed_by_rme', false);
  1073. })
  1074. ->orWhere(function ($q2) use ($performerProID) {
  1075. $q2->where('rmm_pro_id', $performerProID)->where('is_signed_by_rmm', false);
  1076. })
  1077. ->orWhere(function ($q2) use ($performerProID) {
  1078. $q2->where('generic_pro_id', $performerProID)->where('is_signed_by_generic_pro', false);
  1079. });
  1080. })
  1081. ->count();
  1082. $count = DB::select(
  1083. DB::raw(
  1084. "
  1085. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  1086. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  1087. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  1088. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  1089. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  1090. AND (care_month.number_of_days_with_remote_measurements < 16 OR care_month.number_of_days_with_remote_measurements IS NULL)
  1091. "
  1092. )
  1093. );
  1094. $keyNumbers['rmPatientsWithLT16MD'] = $count[0]->cnt;
  1095. $count = DB::select(
  1096. DB::raw(
  1097. "
  1098. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  1099. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  1100. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  1101. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  1102. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  1103. AND (care_month.number_of_days_with_remote_measurements >= 16 AND care_month.number_of_days_with_remote_measurements IS NOT NULL)
  1104. "
  1105. )
  1106. );
  1107. $keyNumbers['rmPatientsWithGTE16MD'] = $count[0]->cnt;
  1108. $count = DB::select(
  1109. DB::raw(
  1110. "
  1111. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  1112. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  1113. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  1114. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  1115. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  1116. 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)
  1117. "
  1118. )
  1119. );
  1120. $keyNumbers['rmPatientsWithWhomCommDone'] = $count[0]->cnt;
  1121. $count = DB::select(
  1122. DB::raw(
  1123. "
  1124. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  1125. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  1126. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  1127. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  1128. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  1129. 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)
  1130. "
  1131. )
  1132. );
  1133. $keyNumbers['rmPatientsWithWhomCommNotDone'] = $count[0]->cnt;
  1134. // num measurements that need stamping
  1135. $keyNumbers['measurementsToBeStamped'] = $this->performer()->pro->getUnstampedMeasurementsFromCurrentMonth(true, null, null);
  1136. if($performer->pro->pro_type === 'ADMIN') {
  1137. // patients without coverage information
  1138. $keyNumbers['patientsWithoutCoverageInformation'] = DB::select(DB::raw("
  1139. SELECT count(DISTINCT (cl.id)) as cnt
  1140. FROM client cl
  1141. WHERE cl.shadow_pro_id IS NULL AND cl.latest_client_primary_coverage_id IS NULL -- no coverage record"
  1142. ))[0]->cnt;
  1143. // patients pending coverage verification
  1144. $keyNumbers['patientsPendingCoverageVerification'] = DB::select(DB::raw("
  1145. SELECT count(DISTINCT (cl.id)) as cnt
  1146. FROM client cl
  1147. LEFT JOIN client_primary_coverage cpc ON cl.latest_client_primary_coverage_id = cpc.id
  1148. WHERE cl.shadow_pro_id IS NULL
  1149. AND (cl.latest_client_primary_coverage_id IS NOT NULL -- coverage exists, but status is null or unknown
  1150. AND (
  1151. (cpc.plan_type = 'MEDICARE' AND (cpc.is_partbprimary = 'UNKNOWN' OR cpc.is_partbprimary IS NULL))
  1152. OR
  1153. (cpc.plan_type != 'MEDICARE' AND
  1154. (cpc.manual_determination_category = 'UNKNOWN' OR cpc.manual_determination_category IS NULL))
  1155. ))"
  1156. ))[0]->cnt;
  1157. }
  1158. return view('app/dashboard-admin', compact('keyNumbers', 'reimbursement', 'milliseconds',
  1159. 'businessNumbers',
  1160. 'incomingReports', 'tickets', 'supplyOrders',
  1161. 'numERx', 'numLabs', 'numImaging', 'numSupplyOrders',
  1162. 'newMCPAssociations', 'newNAAssociations',
  1163. 'mcpClientMemos', 'naClientMemos',
  1164. 'proApptUpdates', 'naApptUpdates'));
  1165. }
  1166. public function dashboard(Request $request)
  1167. {
  1168. $performer = $this->performer();
  1169. $pro = $performer->pro;
  1170. if($pro->pro_type === 'ADMIN'){
  1171. return $this->dashboard_ADMIN($request);
  1172. }elseif($pro->is_enrolled_as_mcp && $pro->is_considered_for_mcp_assignment) {
  1173. return $this->dashboard_MCP($request);
  1174. }elseif($pro->is_hcp){
  1175. return $this->dashboard_HCP($request); //TODO for HCP
  1176. }else{
  1177. return $this->dashboard_DNA($request);
  1178. }
  1179. }
  1180. public function dashboardMeasurementsTab(Request $request, $page = 1) {
  1181. $performer = $this->performer();
  1182. $myClientIDs = [];
  1183. if ($performer->pro->pro_type != 'ADMIN') {
  1184. $myClientIDs = $this->getMyClientIds();
  1185. $myClientIDs = implode(", ", $myClientIDs);
  1186. }
  1187. $ifNotAdmin = " AND (
  1188. client.mcp_pro_id = {$performer->pro->id}
  1189. OR client.rmm_pro_id = {$performer->pro->id}
  1190. OR client.rme_pro_id = {$performer->pro->id}
  1191. OR client.physician_pro_id = {$performer->pro->id}
  1192. OR client.id in (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = {$performer->pro->id})
  1193. OR client.id in (SELECT client_id FROM appointment WHERE status NOT IN ('CANCELLED') AND pro_id = {$performer->pro->id})
  1194. )";
  1195. $numMeasurements = DB::select(
  1196. DB::raw(
  1197. "
  1198. SELECT count(measurement.id) as cnt
  1199. FROM measurement
  1200. join client on measurement.client_id = client.id
  1201. WHERE measurement.label NOT IN ('SBP', 'DBP')
  1202. AND (measurement.is_cellular_zero = FALSE or measurement.is_cellular_zero IS NULL)
  1203. AND measurement.is_active IS TRUE
  1204. AND measurement.has_been_stamped_by_mcp IS FALSE
  1205. AND measurement.ts IS NOT NULL
  1206. AND measurement.client_bdt_measurement_id IS NOT NULL
  1207. AND (measurement.status IS NULL OR (measurement.status <> 'ACK' AND measurement.status <> 'INVALID_ACK'))
  1208. AND EXTRACT(MONTH from measurement.created_at) = EXTRACT(MONTH from NOW())
  1209. AND EXTRACT(YEAR from measurement.created_at) = EXTRACT(YEAR from NOW())
  1210. " .
  1211. (
  1212. $performer->pro->pro_type != 'ADMIN' ? $ifNotAdmin : ''
  1213. )
  1214. )
  1215. );
  1216. $numMeasurements = $numMeasurements[0]->cnt;
  1217. $measurements = DB::select(
  1218. DB::raw(
  1219. "
  1220. SELECT measurement.uid as uid,
  1221. care_month.uid as care_month_uid,
  1222. care_month.start_date as care_month_start_date,
  1223. measurement.label,
  1224. measurement.value,
  1225. measurement.sbp_mm_hg,
  1226. measurement.dbp_mm_hg,
  1227. measurement.numeric_value,
  1228. measurement.value_pulse,
  1229. measurement.value_irregular,
  1230. measurement.ts,
  1231. client.id as client_id,
  1232. client.mcp_pro_id,
  1233. client.default_na_pro_id,
  1234. client.rmm_pro_id,
  1235. client.rme_pro_id,
  1236. client.uid as client_uid,
  1237. client.name_last,
  1238. client.name_first,
  1239. care_month.rm_total_time_in_seconds
  1240. FROM measurement
  1241. join client on measurement.client_id = client.id
  1242. join care_month on client.id = care_month.client_id
  1243. WHERE measurement.label NOT IN ('SBP', 'DBP')
  1244. AND (measurement.is_cellular_zero = FALSE or measurement.is_cellular_zero IS NULL)
  1245. AND measurement.is_active IS TRUE
  1246. AND measurement.has_been_stamped_by_mcp IS FALSE
  1247. AND measurement.ts IS NOT NULL
  1248. AND measurement.client_bdt_measurement_id IS NOT NULL
  1249. AND (measurement.status IS NULL OR (measurement.status <> 'ACK' AND measurement.status <> 'INVALID_ACK'))
  1250. AND EXTRACT(MONTH from measurement.created_at) = EXTRACT(MONTH from NOW())
  1251. AND EXTRACT(YEAR from measurement.created_at) = EXTRACT(YEAR from NOW())
  1252. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from NOW())
  1253. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from NOW())
  1254. " .
  1255. (
  1256. $performer->pro->pro_type != 'ADMIN' ? $ifNotAdmin : ''
  1257. )
  1258. ) .
  1259. " ORDER BY measurement.ts DESC LIMIT 20 OFFSET " . (($page - 1) * 20)
  1260. );
  1261. return view('app.dashboard.measurements', compact('numMeasurements', 'measurements', 'page'));
  1262. }
  1263. public function dashboardAppointmentDates(Request $request, $from, $to) {
  1264. $performer = $this->performer();
  1265. $performerProID = $performer->pro->id;
  1266. $isAdmin = ($performer->pro->pro_type === 'ADMIN');
  1267. $results = DB::table('appointment')->select('raw_date')->distinct()->where("start_time", '>=', $from)->where("start_time", '<=', $to.' 23:59:00+00');
  1268. $results = $results->leftJoin('client AS c', 'c.id', '=', 'appointment.id');
  1269. if(!$isAdmin) {
  1270. $results = $results->where(function($query) use ($performerProID){
  1271. return $query->where('appointment.pro_id', $performerProID)
  1272. ->orWhere('c.default_na_pro_id', $performerProID);
  1273. });
  1274. }
  1275. $results = $results->get();
  1276. $dates = [];
  1277. foreach ($results as $result) {
  1278. // $dates[] = strtotime($result->raw_date) . '000';
  1279. $dates[] = $result->raw_date;
  1280. }
  1281. // foreach ($results as $result) {
  1282. // $results->dateYMD = date('Y-m-d', strtotime($result->raw_date));
  1283. // }
  1284. return json_encode($dates);
  1285. }
  1286. public function dashboardAppointments(Request $request, $from, $to) {
  1287. $performer = $this->performer();
  1288. $performerProID = $performer->pro->id;
  1289. $isAdmin = ($performer->pro->pro_type === 'ADMIN');
  1290. // $appointments = Appointment::where("start_time", '>=', $from)->where("start_time", '<=', $to.' 23:59:00+00');
  1291. $appointments = Appointment::where("raw_date", '=', $from);
  1292. if(!$isAdmin) {
  1293. $appointments = $appointments->where(function($q) use ($performerProID) {
  1294. return $q->where("pro_id", $performerProID)
  1295. ->orWhereHas('client', function($clientQuery) use ($performerProID){
  1296. return $clientQuery->where('default_na_pro_id', $performerProID);
  1297. });
  1298. });
  1299. }
  1300. $appointments = $appointments
  1301. // ->whereRaw('status NOT IN (\'CANCELLED\', \'COMPLETED\')')
  1302. ->orderBy('start_time', 'asc')
  1303. ->get();
  1304. foreach ($appointments as $appointment) {
  1305. $date = explode(" ", $appointment->start_time)[0];
  1306. $appointment->milliseconds = strtotime($date) . '000';
  1307. $appointment->newStatus = $appointment->status;
  1308. $appointment->dateYMD = date('Y-m-d', strtotime($appointment->raw_date));
  1309. $appointment->clientName = $appointment->client->displayName();
  1310. $appointment->clientInitials = substr($appointment->client->name_first, 0, 1) . substr($appointment->client->name_last, 0, 1);
  1311. $appointment->isClientShadowOfPro = $appointment->client->shadow_pro_id ? true : false;
  1312. $appointment->proInitials = substr($appointment->pro->name_first, 0, 1) . substr($appointment->pro->name_last, 0, 1);
  1313. $appointment->friendlyStartTime = friendly_time($appointment->raw_start_time);
  1314. $appointment->friendlyEndTime = friendly_time($appointment->raw_end_time);
  1315. $appointment->clientSummary = friendly_date_time($appointment->client->dob, false) . ' (' .
  1316. $appointment->client->age_in_years . ' y.o' .
  1317. ($appointment->client->sex ? ' ' . $appointment->client->sex : '') .
  1318. ')';
  1319. $appointment->clientAge = $appointment->client->age_in_years;
  1320. $appointment->clientSex = $appointment->client->sex;
  1321. $appointment->started = false;
  1322. $appointment->inHowManyHours = date_diff(date_create('now'), date_create($appointment->start_time), false)
  1323. ->format('%R%h h, %i m');
  1324. if ($appointment->inHowManyHours[0] === '-') {
  1325. $appointment->inHowManyHours = substr($appointment->inHowManyHours, 1) . ' ago';
  1326. $appointment->started = true;
  1327. } else {
  1328. $appointment->inHowManyHours = 'Appt. in ' . substr($appointment->inHowManyHours, 1);
  1329. }
  1330. $appointment->clientUid = $appointment->client->uid;
  1331. $appointment->proUid = $appointment->pro->uid;
  1332. $appointment->proName = $appointment->pro->displayName();
  1333. // insurance information
  1334. $appointment->coverage = $appointment->client->getPrimaryCoverageStatus();
  1335. unset($appointment->client);
  1336. unset($appointment->pro);
  1337. unset($appointment->detail_json);
  1338. }
  1339. return json_encode($appointments);
  1340. }
  1341. public function dashboardAppointmentsDisplay(Request $request, $from, $to) {
  1342. $performer = $this->performer();
  1343. $performerProID = $performer->pro->id;
  1344. $isAdmin = ($performer->pro->pro_type === 'ADMIN');
  1345. // $appointments = Appointment::where("start_time", '>=', $from)->where("start_time", '<=', $to.' 23:59:00+00');
  1346. $appointments = Appointment::where("raw_date", '=', $from);
  1347. if(!$isAdmin) {
  1348. $appointments = $appointments->where(function($q) use ($performerProID) {
  1349. return $q->where("pro_id", $performerProID)
  1350. ->orWhereHas('client', function($clientQuery) use ($performerProID){
  1351. return $clientQuery->where('default_na_pro_id', $performerProID);
  1352. });
  1353. });
  1354. }
  1355. $appointments = $appointments
  1356. ->orderBy('start_time', 'asc')
  1357. ->orderBy('end_time', 'asc')
  1358. ->get();
  1359. foreach ($appointments as $appointment) {
  1360. $date = explode(" ", $appointment->start_time)[0];
  1361. $appointment->milliseconds = strtotime($date) . '000';
  1362. $appointment->newStatus = $appointment->status;
  1363. $appointment->dateYMD = date('Y-m-d', strtotime($appointment->raw_date));
  1364. $appointment->clientName = $appointment->client->displayName();
  1365. $appointment->clientInitials = substr($appointment->client->name_first, 0, 1) . substr($appointment->client->name_last, 0, 1);
  1366. $appointment->isClientShadowOfPro = $appointment->client->shadow_pro_id ? true : false;
  1367. $appointment->proInitials = substr($appointment->pro->name_first, 0, 1) . substr($appointment->pro->name_last, 0, 1);
  1368. $appointment->friendlyStartTime = friendly_time($appointment->raw_start_time);
  1369. $appointment->friendlyEndTime = friendly_time($appointment->raw_end_time);
  1370. $appointment->clientSummary = friendly_date_time($appointment->client->dob, false) . ' (' .
  1371. $appointment->client->age_in_years . ' y.o' .
  1372. ($appointment->client->sex ? ' ' . $appointment->client->sex : '') .
  1373. ')';
  1374. $appointment->clientAge = $appointment->client->age_in_years;
  1375. $appointment->clientSex = $appointment->client->sex;
  1376. $appointment->started = false;
  1377. $appointment->inHowManyHours = date_diff(date_create('now'), date_create($appointment->start_time), false)
  1378. ->format('%R%h h, %i m');
  1379. if ($appointment->inHowManyHours[0] === '-') {
  1380. $appointment->inHowManyHours = substr($appointment->inHowManyHours, 1) . ' ago';
  1381. $appointment->started = true;
  1382. } else {
  1383. $appointment->inHowManyHours = 'Appt. in ' . substr($appointment->inHowManyHours, 1);
  1384. }
  1385. $appointment->clientUid = $appointment->client->uid;
  1386. $appointment->proUid = $appointment->pro->uid;
  1387. $appointment->proName = $appointment->pro->displayName();
  1388. // insurance information
  1389. $appointment->coverage = $appointment->client->getPrimaryCoverageStatus();
  1390. // bg color
  1391. $appointment->bgColor = 'bg-white';
  1392. if($appointment->status === 'COMPLETED') {
  1393. $appointment->bgColor = 'event-bg-green';
  1394. }
  1395. else if($appointment->status === 'CANCELLED') {
  1396. $appointment->bgColor = 'event-bg-gray';
  1397. }
  1398. unset($appointment->client);
  1399. unset($appointment->pro);
  1400. unset($appointment->detail_json);
  1401. }
  1402. return view('app.mcp.dashboard.appointments-list', compact('appointments', 'from', 'to'));
  1403. }
  1404. public function dashboardMeasurements(Request $request, $filter) {
  1405. $measurements = $this->performer()->pro->getMeasurements($filter === 'NEED_ACK');
  1406. return json_encode($measurements);
  1407. }
  1408. public function patients(Request $request, $filter = '')
  1409. {
  1410. $performer = $this->performer();
  1411. $query = $performer->pro->getAccessibleClientsQuery();
  1412. $q = trim($request->input('q'));
  1413. if(!empty($q)) {
  1414. $query = $query->where(function ($query) use ($q) {
  1415. $query->where('name_first', 'ILIKE', "%$q%")
  1416. ->orWhere('name_last', 'ILIKE', "%$q%")
  1417. ->orWhere('email_address', 'ILIKE', "%$q%")
  1418. ->orWhere('tags', 'ILIKE', "%$q%");
  1419. });
  1420. }
  1421. switch ($filter) {
  1422. case 'not-yet-seen':
  1423. $query = $query
  1424. ->where(function ($query) use ($performer) {
  1425. $query
  1426. ->where(function ($query) use ($performer) { // own patient and primary OB visit pending
  1427. $query->where('mcp_pro_id', $performer->pro->id)
  1428. ->where('has_mcp_done_onboarding_visit', '<>', 'YES');
  1429. })
  1430. ->orWhere(function ($query) use ($performer) { // mcp of any client program and program OB pending
  1431. $query->select(DB::raw('COUNT(id)'))
  1432. ->from('client_program')
  1433. ->whereColumn('client_id', 'client.id')
  1434. ->where('mcp_pro_id', $performer->pro->id)
  1435. ->where('has_mcp_done_onboarding_visit', '<>', 'YES');
  1436. }, '>=', 1);
  1437. });
  1438. break;
  1439. case 'having-birthday-today':
  1440. $query = $query
  1441. ->whereRaw('EXTRACT(DAY from dob) = ?', [date('d')])
  1442. ->whereRaw('EXTRACT(MONTH from dob) = ?', [date('m')]);
  1443. break;
  1444. // more cases can be added as needed
  1445. default:
  1446. break;
  1447. }
  1448. $patients = $query->orderBy('created_at', 'desc')->paginate(50);
  1449. // patient acquisition chart (admin only)
  1450. $patientAcquisitionData = null;
  1451. if($performer->pro->pro_type === 'ADMIN') {
  1452. $startDate = date_sub(date_create(), date_interval_create_from_date_string("1 month"));
  1453. $startDate = date_format($startDate, "Y-m-d");
  1454. $patientAcquisitionData = DB::select(DB::raw(
  1455. "SELECT count(id) as count, DATE(created_at at time zone 'utc' at time zone 'est') as date " .
  1456. "FROM client " .
  1457. "WHERE shadow_pro_id IS NULL " .
  1458. "GROUP BY DATE(created_at at time zone 'utc' at time zone 'est') " .
  1459. "ORDER BY DATE(created_at at time zone 'utc' at time zone 'est') DESC " .
  1460. "LIMIT 30"));
  1461. }
  1462. return view('app/patients', compact('patients', 'filter', 'patientAcquisitionData'));
  1463. }
  1464. public function patientsSuggest(Request $request)
  1465. {
  1466. $pro = $this->pro;
  1467. $term = $request->input('term') ? trim($request->input('term')) : '';
  1468. $originalTerm = $term;
  1469. if (empty($term)) return '';
  1470. // if multiple words in query, check for all (max 2)
  1471. $term2 = '';
  1472. if(strpos($term, ' ') !== FALSE) {
  1473. $terms = explode(' ', $term);
  1474. $term = trim($terms[0]);
  1475. $term2 = trim($terms[1]);
  1476. }
  1477. $phoneNumberTerm = preg_replace("/[^0-9]/", "", $originalTerm );
  1478. if($phoneNumberTerm == ""){ //to avoid search with blank string
  1479. $phoneNumberTerm = $term;
  1480. }
  1481. $clientQuery= Client::whereNull('shadow_pro_id')
  1482. ->where(function ($q) use ($term, $phoneNumberTerm) {
  1483. $q->where('name_first', 'ILIKE', '%' . $term . '%')
  1484. ->orWhere('name_last', 'ILIKE', '%' . $term . '%')
  1485. ->orWhere('cell_number', 'ILIKE', '%' . $phoneNumberTerm . '%')
  1486. ->orWhere('phone_home', 'ILIKE', '%' . $phoneNumberTerm . '%');
  1487. });
  1488. if(!empty($term2)) {
  1489. $clientQuery = $clientQuery->where(function ($q) use ($term2, $phoneNumberTerm) {
  1490. $q->where('name_first', 'ILIKE', '%' . $term2 . '%')
  1491. ->orWhere('name_last', 'ILIKE', '%' . $term2 . '%')
  1492. ->orWhere('cell_number', 'ILIKE', '%' . $phoneNumberTerm . '%')
  1493. ->orWhere('phone_home', 'ILIKE', '%' . $phoneNumberTerm . '%');
  1494. });
  1495. }
  1496. if(!($pro->pro_type === 'ADMIN' && $pro->can_see_any_client_via_search)) {
  1497. $clientQuery->where(function ($q) use ($pro) {
  1498. if($pro->pro_type === 'ADMIN' || $pro->is_enrolled_as_mcp) {
  1499. $q->whereIn('id', $pro->getMyClientIds(true))->orWhereNull('mcp_pro_id');
  1500. }
  1501. else {
  1502. $q->whereIn('id', $pro->getMyClientIds(true));
  1503. }
  1504. });
  1505. }
  1506. $clients = $clientQuery->get();
  1507. return view('app/patient-suggest', compact('clients'));
  1508. }
  1509. public function pharmacySuggest(Request $request)
  1510. {
  1511. $term = $request->input('term') ? trim($request->input('term')) : '';
  1512. if (empty($term)) return '';
  1513. $term = strtolower($term);
  1514. $pharmacies = Facility::where('facility_type', 'Pharmacy')
  1515. ->where(function ($q) use ($term) {
  1516. $q->orWhereRaw('LOWER(name::text) LIKE ?', ['%' . $term . '%'])
  1517. ->orWhereRaw('LOWER(address_line1::text) LIKE ?', ['%' . $term . '%'])
  1518. ->orWhereRaw('LOWER(address_line2::text) LIKE ?', ['%' . $term . '%'])
  1519. ->orWhereRaw('LOWER(address_city::text) LIKE ?', ['%' . $term . '%'])
  1520. ->orWhereRaw('LOWER(address_state::text) LIKE ?', ['%' . $term . '%'])
  1521. ->orWhereRaw('LOWER(phone::text) LIKE ?', ['%' . $term . '%'])
  1522. ->orWhereRaw('LOWER(address_zip::text) LIKE ?', ['%' . $term . '%']);
  1523. });
  1524. if($request->input('city')) {
  1525. $pharmacies = $pharmacies->whereRaw('LOWER(address_city::text) LIKE ?', ['%' . strtolower($request->input('city')) . '%']);
  1526. }
  1527. if($request->input('state')) {
  1528. $pharmacies = $pharmacies->whereRaw('LOWER(address_state::text) LIKE ?', ['%' . strtolower($request->input('state')) . '%']);
  1529. }
  1530. if($request->input('zip')) {
  1531. $pharmacies = $pharmacies->whereRaw('LOWER(address_zip::text) LIKE ?', ['%' . strtolower($request->input('zip')) . '%']);
  1532. }
  1533. $pharmacies = $pharmacies
  1534. ->orderBy('name', 'asc')
  1535. ->orderBy('address_line1', 'asc')
  1536. ->orderBy('address_city', 'asc')
  1537. ->orderBy('address_state', 'asc')
  1538. ->get();
  1539. return view('app/pharmacy-suggest', compact('pharmacies'));
  1540. }
  1541. public function facilitySuggestJSON(Request $request)
  1542. {
  1543. $term = $request->input('term') ? trim($request->input('term')) : '';
  1544. if (empty($term)) return '';
  1545. $terms = explode(' ', $term);
  1546. $terms = array_filter($terms, function($_x) {
  1547. return !!trim($_x);
  1548. });
  1549. $whereCondition = [];
  1550. $whereParams = [];
  1551. for ($i = 0; $i < count($terms); $i++) {
  1552. $whereCondition[] = "(name ILIKE :term{$i} OR address_city ILIKE :term{$i} OR address_state ILIKE :term{$i} OR address_zip ILIKE :term{$i})";
  1553. $whereParams["term{$i}"] = '%' . $terms[$i] . '%';
  1554. }
  1555. $whereCondition = implode(" AND ", $whereCondition);
  1556. $matches = DB::select(
  1557. "SELECT (name || ' ' || address_city || ' ' || address_state || ' ' || address_zip) as text,
  1558. address_line1 as text2,
  1559. name, address_city as city, address_state as state, address_zip as zip, phone, fax FROM facility
  1560. WHERE {$whereCondition} ORDER BY name", $whereParams);
  1561. return json_encode([
  1562. "success" => true,
  1563. "data" => $matches
  1564. ]);
  1565. }
  1566. public function proSuggest(Request $request) {
  1567. $term = $request->input('term') ? trim($request->input('term')) : '';
  1568. if (empty($term)) return '';
  1569. $term = strtolower($term);
  1570. // if multiple words in query, check for all (max 2)
  1571. $term2 = '';
  1572. if(strpos($term, ' ') !== FALSE) {
  1573. $terms = explode(' ', $term);
  1574. $term = trim($terms[0]);
  1575. $term2 = trim($terms[1]);
  1576. }
  1577. $pros = Pro::where(function ($q) use ($term) {
  1578. $q->orWhereRaw('LOWER(name_first::text) LIKE ?', ['%' . $term . '%'])
  1579. ->orWhereRaw('LOWER(name_last::text) LIKE ?', ['%' . $term . '%'])
  1580. ->orWhereRaw('cell_number LIKE ?', ['%' . $term . '%']);
  1581. });
  1582. if(!empty($term2)) {
  1583. $pros = $pros->where(function ($q) use ($term2) {
  1584. $q->orWhereRaw('LOWER(name_first::text) LIKE ?', ['%' . $term2 . '%'])
  1585. ->orWhereRaw('LOWER(name_last::text) LIKE ?', ['%' . $term2 . '%'])
  1586. ->orWhereRaw('cell_number LIKE ?', ['%' . $term2 . '%']);
  1587. });
  1588. }
  1589. $type = $request->input('type') ? trim($request->input('type')) : '';
  1590. if(!!$type) {
  1591. switch(strtolower($type)) {
  1592. case 'hcp':
  1593. $pros->where('is_hcp', true);
  1594. break;
  1595. case 'default-na': // TODO: fix condition for NA
  1596. $pros->where('is_hcp', false)->where('pro_type', '!=', 'ADMIN');
  1597. break;
  1598. case 'admin':
  1599. $pros->where('pro_type', 'ADMIN');
  1600. break;
  1601. case 'non-admin':
  1602. $pros->where('pro_type', '!=', 'ADMIN');
  1603. break;
  1604. }
  1605. }
  1606. if($this->performer->pro && $this->performer->pro->pro_type != 'ADMIN'){
  1607. $accessiblePros = ProProAccess::where('owner_pro_id', $this->performer->pro->id);
  1608. $accessibleProIds = [];
  1609. foreach($accessiblePros as $accessiblePro){
  1610. $accessibleProIds[] = $accessiblePro->id;
  1611. }
  1612. $accessibleProIds[] = $this->performer->pro->id;
  1613. // for dna, add pros accessible via pro teams
  1614. if($this->performer->pro->isDefaultNA()) {
  1615. $teams = $this->performer->pro->teamsWhereAssistant;
  1616. foreach ($teams as $team) {
  1617. if(!in_array($team->mcp_pro_id, $accessibleProIds)) {
  1618. $accessibleProIds[] = $team->mcp_pro_id;
  1619. }
  1620. }
  1621. }
  1622. $pros->whereIn('id', $accessibleProIds);
  1623. }
  1624. $suggestedPros = $pros->orderBy('name_last')->orderBy('name_first')->get();
  1625. // for calendar select2
  1626. if($request->input('json')) {
  1627. $jsonPros = $suggestedPros->map(function($_pro) {
  1628. return [
  1629. "uid" => $_pro->uid,
  1630. "id" => $_pro->id,
  1631. "text" => $_pro->displayName(),
  1632. "initials" => $_pro->initials(),
  1633. ];
  1634. });
  1635. return json_encode([
  1636. "results" => $jsonPros
  1637. ]);
  1638. }
  1639. return view('app/pro-suggest', compact('suggestedPros'));
  1640. }
  1641. public function canAccessPatient(Request $request, $uid) {
  1642. return json_encode([
  1643. "success" => true,
  1644. "data" => $this->performer->pro->canAccess($uid)
  1645. ]);
  1646. }
  1647. public function proDisplayName(Request $request, Pro $pro) {
  1648. return $pro ? $pro->displayName() : '';
  1649. }
  1650. public function unmappedSMS(Request $request, $filter = '')
  1651. {
  1652. $proID = $this->performer()->pro->id;
  1653. if ($this->performer()->pro->pro_type === 'ADMIN') {
  1654. $query = Client::where('id', '>', 0);
  1655. } else {
  1656. $query = Client::where(function ($q) use ($proID) {
  1657. $q->where('mcp_pro_id', $proID)
  1658. ->orWhere('cm_pro_id', $proID)
  1659. ->orWhere('rmm_pro_id', $proID)
  1660. ->orWhere('rme_pro_id', $proID)
  1661. ->orWhereRaw('id IN (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = ?)', [$proID]);
  1662. });
  1663. }
  1664. $patients = $query->orderBy('name_last', 'asc')->orderBy('name_first', 'asc')->get();
  1665. $unmappedSMS = ClientSMS::where('client_id', null)->where('incoming_or_outgoing', 'INCOMING')->paginate(20);
  1666. return view('app/unmapped-sms', compact('unmappedSMS', 'patients'));
  1667. }
  1668. public function newPatient(Request $request)
  1669. {
  1670. $mbPayers = MBPayer::all();
  1671. return view('app/new-patient', compact('mbPayers'));
  1672. }
  1673. public function newNonMcnPatient(Request $request)
  1674. {
  1675. $mbPayers = MBPayer::all();
  1676. return view('app/new-non-mcn-patient', compact('mbPayers'));
  1677. }
  1678. public function mc(Request $request, $fragment = "")
  1679. {
  1680. $page = "/";
  1681. if ($fragment) {
  1682. $page = '/' . $fragment;
  1683. }
  1684. return view('app/mc', compact('page'));
  1685. }
  1686. public function blank(Request $request)
  1687. {
  1688. return view('app/blank');
  1689. }
  1690. public function noteTemplateSet(Request $request, $section, $template)
  1691. {
  1692. return view('app/patient/note/_template', [
  1693. "sectionInternalName" => $section,
  1694. "templateName" => $template
  1695. ]);
  1696. }
  1697. public function noteExamTemplateSet(Request $request, $exam, $template)
  1698. {
  1699. return view('app/patient/note/_template-exam', [
  1700. "exam" => $exam,
  1701. "sectionInternalName" => 'exam-' . $exam . '-detail',
  1702. "templateName" => $template
  1703. ]);
  1704. }
  1705. public function logInAs(Request $request)
  1706. {
  1707. if($this->pro->pro_type != 'ADMIN'){
  1708. return redirect()->to(route('dashboard'));
  1709. }
  1710. // dummy condition to get the chain-ability going
  1711. $pros = Pro::where('id', '>', 0);
  1712. if($request->input('q')) {
  1713. $nameQuery = '%' . $request->input('q') . '%';
  1714. $pros = $pros->where(function ($query) use ($nameQuery) {
  1715. $query->where('name_first', 'ILIKE', $nameQuery)
  1716. ->orWhere('name_last', 'ILIKE', $nameQuery)
  1717. ->orWhere('email_address', 'ILIKE', $nameQuery)
  1718. ->orWhere('cell_number', 'ILIKE', $nameQuery);
  1719. });
  1720. }
  1721. if($request->input('sort') && $request->input('dir')) {
  1722. $pros = $pros->orderBy($request->input('sort'), $request->input('dir'));
  1723. }
  1724. else {
  1725. $pros = $pros->orderBy('name_last', 'asc');
  1726. }
  1727. $pros = $pros->paginate(20);
  1728. return view('app/log-in-as', ['logInAsPros' => $pros]);
  1729. }
  1730. public function processLogInAs(Request $request)
  1731. {
  1732. $api = new Backend();
  1733. try {
  1734. $apiResponse = $api->post('session/proLogInAs', [
  1735. 'proUid' => $request->post('proUid')
  1736. ],
  1737. [
  1738. 'sessionKey'=>$this->performer()->session_key
  1739. ]);
  1740. $data = json_decode($apiResponse->getContents());
  1741. if (!property_exists($data, 'success') || !$data->success) {
  1742. return redirect()->to(route('log-in-as'))->with('message', $data->message)
  1743. ->withInput($request->input());
  1744. }
  1745. Cookie::queue('sessionKey', $data->data->sessionKey);
  1746. return redirect('/mc');
  1747. } catch (\Exception $e) {
  1748. return redirect()->to(route('log-in-as'))
  1749. ->with('message', 'Unable to process your request at the moment. Please try again later.')
  1750. ->withInput($request->input());
  1751. }
  1752. }
  1753. public function backToAdminPro(Request $request){
  1754. $adminPerformerId = $this->performer->logged_in_as_pro_from_admin_pro_app_session_id;
  1755. $adminPerformer = AppSession::where('id', $adminPerformerId)->first();
  1756. $url = "/session/pro_log_in_with_session_key/".$adminPerformer->session_key;
  1757. $api = new Backend();
  1758. try {
  1759. $apiResponse = $api->post($url, []);
  1760. $data = json_decode($apiResponse->getContents());
  1761. if (!property_exists($data, 'success') || !$data->success) {
  1762. return redirect()->to(route('logout'));
  1763. }
  1764. Cookie::queue('sessionKey', $data->data->sessionKey);
  1765. return redirect(route('dashboard'));
  1766. } catch (\Exception $e) {
  1767. return redirect(route('dashboard'));
  1768. }
  1769. }
  1770. public function getTicket(Request $request, Ticket $ticket) {
  1771. $ticket->data = json_decode($ticket->data);
  1772. // $ticket->created_at = friendly_date_time($ticket->created_at);
  1773. $ticket->assignedPro;
  1774. $ticket->managerPro;
  1775. $ticket->orderingPro;
  1776. $ticket->initiatingPro;
  1777. return json_encode($ticket);
  1778. }
  1779. public function genericBill(Request $request, $entityType, $entityUid) {
  1780. $patient = null;
  1781. if ($entityType && $entityUid) {
  1782. try {
  1783. $entityClass = "\\App\\Models\\" . $entityType;
  1784. $entity = $entityClass::where('uid', $entityUid)->first();
  1785. if ($entity->client) {
  1786. $patient = $entity->client;
  1787. }
  1788. } catch (\Exception $e) {
  1789. }
  1790. }
  1791. return view('app.generic-bills.inline', ['class' => 'p-3 border-top mt-3', 'entityType' => $entityType, 'entityUid' => $entityUid, 'patient' => $patient]);
  1792. }
  1793. public function outgoingEmailTemplates(Request $request){
  1794. $templates = OutgoingEmailTemplate::where('is_active', true)->orderBy('default_subject_tpl', 'ASC')->get();
  1795. return $this->pass($templates);
  1796. }
  1797. }