HomeController.php 91 KB

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