HomeController.php 97 KB

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