HomeController.php 96 KB

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