HomeController.php 91 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964
  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. $careMonthsWithMeasurementsPendingStamping = CareMonth::select('id')
  467. ->where('mcp_pro_id', $this->performer->pro->id)
  468. ->where('rm_num_measurements_not_stamped_by_mcp', '>', 0)
  469. ->whereNotNull('rm_num_measurements_not_stamped_by_mcp')
  470. ->orderBy('created_at', 'DESC')
  471. ->get()
  472. ->map(function($_x) {
  473. return $_x->id;
  474. })
  475. ->toArray();
  476. $measurementsPendingStamping = Measurement::whereIn('care_month_id', $careMonthsWithMeasurementsPendingStamping)
  477. ->orderBy('created_at', 'DESC')
  478. ->whereNotNull('ts')
  479. ->whereNotIn('label', ['SBP', 'DBP'])
  480. ->where('is_cellular_zero', '<>', true)
  481. ->where('is_removed', false)
  482. ->where('has_been_stamped_by_mcp', false)
  483. ->whereNotNull('client_bdt_measurement_id')
  484. ->paginate(15);
  485. return view('app/dashboard-mcp', compact('keyNumbers', 'reimbursement', 'milliseconds',
  486. 'businessNumbers',
  487. 'incomingReports', 'tickets', 'supplyOrders',
  488. 'numERx', 'numLabs', 'numImaging', 'numSupplyOrders',
  489. 'newMCPAssociations', 'newNAAssociations',
  490. 'measurementsPendingStamping', 'careMonthsWithMeasurementsPendingStamping',
  491. 'mcpClientMemos', 'mcpClientMemosCount', 'naClientMemos', 'incomingSmsMessagesPendingReply'));
  492. }
  493. private function dashboard_DNA(Request $request){
  494. $performer = $this->performer();
  495. $pro = $performer->pro;
  496. $keyNumbers = [];
  497. // Patients // SELECT * FROM client WHERE mcp_pro_id = :me.id;
  498. // New Patients Awaiting Visit // SELECT * FROM client WHERE mcp_pro_id = :me.id AND hasMcpDoneOnboardingVisit != 'YES';
  499. // 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;
  500. // 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;
  501. // Reports Pending Signature // SELECT * FROM incoming_report WHERE hcp_pro_id = :me.id AND isEntryError IS NOT TRUE AND hasHcpProSigned IS NOT TRUE;
  502. // Patients w/o Appointments // SELECT * FROM client WHERE mcp_pro_id = :me.id AND client.next_mcp_appointment_date < today();
  503. // Patients Overdue for Visit // SELECT * FROM client WHERE mcp_pro_id = :me.id AND client.next_expected_mcp_visit_date < today();
  504. // Cancelled Appts. Pending Review // SELECT * FROM appointment WHERE hcp_pro_id = :me.id AND status = 'REJECTED' AND wasAcknowledgedByAppointmentPro IS NOT TRUE;
  505. // Cancelled Bills Pending Review // SELECT * FROM bill WHERE bill_service_type = 'NOTE' AND is_cancelled IS TRUE AND isCancellationAcknowledged IS FALSE;
  506. // 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;
  507. // ERx & Orders Pending Signature // SELECT * FROM erx WHERE hcp_pro_id = :me.id AND pro_declared_status <> 'CANCELLED' AND hasHcpProSigned IS NOT TRUE;
  508. // 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;
  509. $performer = $this->performer();
  510. $pro = $performer->pro;
  511. $performerProID = $performer->pro->id;
  512. $keyNumbers = [];
  513. $queryClients = $this->performer()->pro->getAccessibleClientsQuery();
  514. $keyNumbers['patients'] = $queryClients->count();
  515. $pendingNotesToSign = Note::where('ally_pro_id', $performerProID)->where('is_signed_by_ally', false)->where('is_cancelled', false)->where('is_core_note', false)->count();
  516. $keyNumbers['pendingNotesToSign'] = $pendingNotesToSign;
  517. // notes pending mcp sign (applicable to dnas only)
  518. $pendingNotesToSignMCP = Note::where('ally_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_cancelled', false)->where('is_core_note', false)->count();
  519. $keyNumbers['$pendingNotesToSignMCP'] = $pendingNotesToSignMCP;
  520. $pendingNotesToSignAllySigned = Note::where(function ($query) use ($performerProID) {
  521. $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);
  522. })->count();
  523. $keyNumbers['pendingNotesToSignAllySigned'] = $pendingNotesToSignAllySigned;
  524. $signedNotesWithoutBills = Note::where(function ($query) use ($performerProID) {
  525. $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', true)->where('is_cancelled', false);
  526. })->whereDoesntHave('bills')->count();
  527. $keyNumbers['signedNotesWithoutBills'] = $signedNotesWithoutBills;
  528. // open tickets
  529. $keyNumbers['numOpenTickets'] = Ticket::where('is_open', true)
  530. ->where(function ($q) use ($performerProID) {
  531. $q->where('assigned_pro_id', $performerProID)
  532. ->orWhere('manager_pro_id', $performerProID)
  533. ->orWhere('ordering_pro_id', $performerProID)
  534. ->orWhere('initiating_pro_id', $performerProID);
  535. })
  536. ->count();
  537. // unacknowledged cancelled bills for authed pro
  538. $keyNumbers['unacknowledgedCancelledBills'] = Bill::where('na_pro_id', $performerProID)
  539. ->where('is_cancelled', true)
  540. ->where('is_cancellation_acknowledged', false)
  541. ->count();
  542. // unacknowledged cancelled supply orders for authed pro
  543. $keyNumbers['unacknowledgedCancelledSupplyOrders'] = SupplyOrder::where('signed_by_pro_id', $performerProID)
  544. ->where('is_cancelled', true)
  545. ->where('is_cancellation_acknowledged', false)
  546. ->count();
  547. // unsigned supply orders created by authed pro
  548. $keyNumbers['unsignedSupplyOrders'] = SupplyOrder
  549. ::where('is_cancelled', false)
  550. ->where('is_signed_by_pro', false)
  551. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session WHERE pro_id = ?)', [$performerProID])
  552. ->count();
  553. // patientsHavingBirthdayToday
  554. $queryClients = $this->performer()->pro->getAccessibleClientsQuery();
  555. $keyNumbers['patientsHavingBirthdayToday'] = $queryClients
  556. ->whereRaw('EXTRACT(DAY from dob) = ?', [date('d')])
  557. ->whereRaw('EXTRACT(MONTH from dob) = ?', [date('m')])
  558. ->count();
  559. $reimbursement = [];
  560. $reimbursement["currentBalance"] = $performer->pro->balance;
  561. $reimbursement["nextPaymentDate"] = '--';
  562. $lastPayment = ProTransaction::where('pro_id', $performerProID)->where('plus_or_minus', 'PLUS')->orderBy('created_at', 'DESC')->first();
  563. if ($lastPayment) {
  564. $reimbursement["lastPayment"] = $lastPayment->amount;
  565. $reimbursement["lastPaymentDate"] = $lastPayment->created_at;
  566. } else {
  567. $reimbursement["lastPayment"] = '--';
  568. $reimbursement["lastPaymentDate"] = '--';
  569. }
  570. //if today is < 15th, next payment is 15th, else nextPayment is
  571. $today = strtotime(date('Y-m-d'));
  572. $todayDate = date('j', $today);
  573. $todayMonth = date('m', $today);
  574. $todayYear = date('Y', $today);
  575. if ($todayDate < 15) {
  576. $nextPaymentDate = new DateTime();
  577. $nextPaymentDate->setDate($todayYear, $todayMonth, 15);
  578. $reimbursement['nextPaymentDate'] = $nextPaymentDate->format('m/d/Y');
  579. } else {
  580. $nextPaymentDate = new \DateTime();
  581. $lastDayOfMonth = date('t', $today);
  582. $nextPaymentDate->setDate($todayYear, $todayMonth, $lastDayOfMonth);
  583. $reimbursement['nextPaymentDate'] = $nextPaymentDate->format('m/d/Y');
  584. }
  585. //expectedPay
  586. $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;
  587. $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;
  588. $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;
  589. $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;
  590. $totalExpectedAmount = $expectedForCm + $expectedForRme + $expectedForRmm + $expectedForNa;
  591. $reimbursement['nextPaymentAmount'] = $totalExpectedAmount;
  592. $milliseconds = strtotime(date('Y-m-d')) . '000';
  593. // bills & claims
  594. $businessNumbers = [];
  595. // Notes with bills to resolve
  596. $businessNumbers['notesWithBillsToResolve'] = Note::where('is_cancelled', '!=', true)
  597. ->where('is_bill_closed', '!=', true)
  598. ->whereRaw('(SELECT count(id) FROM bill WHERE note_id = note.id AND is_cancelled = false AND is_verified = false) > 0')
  599. ->count();
  600. // Notes pending bill closure
  601. $businessNumbers['notesPendingBillingClosure'] = Note::where('is_cancelled', '!=', true)
  602. ->where('is_bill_closed', '!=', true)
  603. ->whereRaw('(SELECT count(id) FROM bill WHERE note_id = note.id AND (is_cancelled = true OR is_verified = true)) = 0')
  604. ->count();
  605. // incoming reports not signed
  606. $incomingReports = IncomingReport::where('hcp_pro_id', $performerProID)
  607. ->where('has_hcp_pro_signed', false)
  608. ->where('is_entry_error', false)
  609. ->orderBy('created_at', 'ASC')
  610. ->get();
  611. // erx, labs & imaging that are not closed
  612. $tickets = Ticket::where('ordering_pro_id', $performerProID)
  613. ->where('is_entry_error', false)
  614. ->where('is_open', true)
  615. ->orderBy('created_at', 'ASC')
  616. ->get();
  617. $supplyOrders = SupplyOrder::where('is_cleared_for_shipment', false)
  618. ->where('is_cancelled', false)
  619. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session where pro_id = ?)', [$performer->pro->id])
  620. ->orderBy('created_at', 'ASC')
  621. ->get();
  622. $numERx = Ticket::where('ordering_pro_id', $performerProID)
  623. ->where('category', 'erx')
  624. ->where('is_entry_error', false)
  625. ->where('is_open', true)
  626. ->count();
  627. $numLabs = Ticket::where('ordering_pro_id', $performerProID)
  628. ->where('category', 'lab')
  629. ->where('is_entry_error', false)
  630. ->where('is_open', true)
  631. ->count();
  632. $numImaging = Ticket::where('ordering_pro_id', $performerProID)
  633. ->where('category', 'imaging')
  634. ->where('is_entry_error', false)
  635. ->where('is_open', true)
  636. ->count();
  637. $numSupplyOrders = SupplyOrder::where('is_cleared_for_shipment', false)
  638. ->where('is_cancelled', false)
  639. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session where pro_id = ?)', [$performer->pro->id])
  640. ->count();
  641. $newMCPAssociations = ClientProChange
  642. ::where('new_pro_id', $performerProID)
  643. ->where('responsibility_type', 'MCP')
  644. ->whereNull('current_client_pro_change_decision_id')
  645. ->get();
  646. $newNAAssociations = ClientProChange
  647. ::where('new_pro_id', $performerProID)
  648. ->where('responsibility_type', 'DEFAULT_NA')
  649. ->whereNull('current_client_pro_change_decision_id')
  650. ->get();
  651. // unstamped client memos
  652. // for mcp
  653. $mcpClientMemos = DB::select(
  654. DB::raw("
  655. SELECT c.uid as client_uid, c.name_first, c.name_last,
  656. cm.uid, cm.content, cm.created_at
  657. FROM client c join client_memo cm on c.id = cm.client_id
  658. WHERE
  659. c.mcp_pro_id = {$performerProID} AND
  660. cm.mcp_stamp_id IS NULL
  661. ORDER BY cm.created_at DESC
  662. ")
  663. );
  664. // for na
  665. $naClientMemos = DB::select(
  666. DB::raw("
  667. SELECT c.uid as client_uid, c.name_first, c.name_last,
  668. cm.uid, cm.content, cm.created_at
  669. FROM client c join client_memo cm on c.id = cm.client_id
  670. WHERE
  671. c.default_na_pro_id = {$performerProID} AND
  672. cm.default_na_stamp_id IS NULL
  673. ORDER BY cm.created_at DESC
  674. ")
  675. );
  676. $keyNumbers['rmBillsToSign'] = Bill
  677. ::where('is_cancelled', false)
  678. ->where('cm_or_rm', 'RM')
  679. ->where(function ($q) use ($performerProID) {
  680. $q
  681. ->where(function ($q2) use ($performerProID) {
  682. $q2->where('rme_pro_id', $performerProID)->where('is_signed_by_rme', false);
  683. })
  684. ->orWhere(function ($q2) use ($performerProID) {
  685. $q2->where('rmm_pro_id', $performerProID)->where('is_signed_by_rmm', false);
  686. })
  687. ->orWhere(function ($q2) use ($performerProID) {
  688. $q2->where('generic_pro_id', $performerProID)->where('is_signed_by_generic_pro', false);
  689. });
  690. })
  691. ->count();
  692. $count = DB::select(
  693. DB::raw(
  694. "
  695. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  696. WHERE ( (client.rmm_pro_id = {$performer->pro->id})
  697. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  698. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  699. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  700. AND (care_month.number_of_days_with_remote_measurements < 16 OR care_month.number_of_days_with_remote_measurements IS NULL)
  701. "
  702. )
  703. );
  704. $keyNumbers['rmPatientsWithLT16MD'] = $count[0]->cnt;
  705. $count = DB::select(
  706. DB::raw(
  707. "
  708. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  709. WHERE ((client.rmm_pro_id = {$performer->pro->id})
  710. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  711. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  712. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  713. AND (care_month.number_of_days_with_remote_measurements >= 16 AND care_month.number_of_days_with_remote_measurements IS NOT NULL)
  714. "
  715. )
  716. );
  717. $keyNumbers['rmPatientsWithGTE16MD'] = $count[0]->cnt;
  718. $count = DB::select(
  719. DB::raw(
  720. "
  721. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  722. WHERE ((client.rmm_pro_id = {$performer->pro->id})
  723. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  724. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  725. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  726. 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)
  727. "
  728. )
  729. );
  730. $keyNumbers['rmPatientsWithWhomCommDone'] = $count[0]->cnt;
  731. $count = DB::select(
  732. DB::raw(
  733. "
  734. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  735. WHERE ( (client.rmm_pro_id = {$performer->pro->id})
  736. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  737. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  738. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  739. 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)
  740. "
  741. )
  742. );
  743. $keyNumbers['rmPatientsWithWhomCommNotDone'] = $count[0]->cnt;
  744. // num measurements that need stamping
  745. $keyNumbers['measurementsToBeStamped'] = $this->performer()->pro->getUnstampedMeasurementsFromCurrentMonth(true, null, null);
  746. if($performer->pro->pro_type === 'ADMIN') {
  747. // patients without coverage information
  748. $keyNumbers['patientsWithoutCoverageInformation'] = DB::select(DB::raw("
  749. SELECT count(DISTINCT (cl.id)) as cnt
  750. FROM client cl
  751. WHERE cl.shadow_pro_id IS NULL AND cl.latest_client_primary_coverage_id IS NULL -- no coverage record"
  752. ))[0]->cnt;
  753. // patients pending coverage verification
  754. $keyNumbers['patientsPendingCoverageVerification'] = DB::select(DB::raw("
  755. SELECT count(DISTINCT (cl.id)) as cnt
  756. FROM client cl
  757. LEFT JOIN client_primary_coverage cpc ON cl.latest_client_primary_coverage_id = cpc.id
  758. WHERE cl.shadow_pro_id IS NULL
  759. AND (cl.latest_client_primary_coverage_id IS NOT NULL -- coverage exists, but status is null or unknown
  760. AND (
  761. (cpc.plan_type = 'MEDICARE' AND (cpc.is_partbprimary = 'UNKNOWN' OR cpc.is_partbprimary IS NULL))
  762. OR
  763. (cpc.plan_type != 'MEDICARE' AND
  764. (cpc.manual_determination_category = 'UNKNOWN' OR cpc.manual_determination_category IS NULL))
  765. ))"
  766. ))[0]->cnt;
  767. }
  768. return view('app/dashboard-dna', compact('keyNumbers', 'reimbursement', 'milliseconds',
  769. 'businessNumbers',
  770. 'incomingReports', 'tickets', 'supplyOrders',
  771. 'numERx', 'numLabs', 'numImaging', 'numSupplyOrders',
  772. 'newMCPAssociations', 'newNAAssociations',
  773. 'mcpClientMemos', 'naClientMemos'));
  774. }
  775. private function dashboard_ADMIN(Request $request){
  776. $keyNumbers = [];
  777. // Patients // SELECT * FROM client WHERE mcp_pro_id = :me.id;
  778. // New Patients Awaiting Visit // SELECT * FROM client WHERE mcp_pro_id = :me.id AND hasMcpDoneOnboardingVisit != 'YES';
  779. // 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;
  780. // 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;
  781. // Reports Pending Signature // SELECT * FROM incoming_report WHERE hcp_pro_id = :me.id AND isEntryError IS NOT TRUE AND hasHcpProSigned IS NOT TRUE;
  782. // Patients w/o Appointments // SELECT * FROM client WHERE mcp_pro_id = :me.id AND client.next_mcp_appointment_date < today();
  783. // Patients Overdue for Visit // SELECT * FROM client WHERE mcp_pro_id = :me.id AND client.next_expected_mcp_visit_date < today();
  784. // Cancelled Appts. Pending Review // SELECT * FROM appointment WHERE hcp_pro_id = :me.id AND status = 'REJECTED' AND wasAcknowledgedByAppointmentPro IS NOT TRUE;
  785. // Cancelled Bills Pending Review // SELECT * FROM bill WHERE bill_service_type = 'NOTE' AND is_cancelled IS TRUE AND isCancellationAcknowledged IS FALSE;
  786. // 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;
  787. // ERx & Orders Pending Signature // SELECT * FROM erx WHERE hcp_pro_id = :me.id AND pro_declared_status <> 'CANCELLED' AND hasHcpProSigned IS NOT TRUE;
  788. // 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;
  789. $performer = $this->performer();
  790. $pro = $performer->pro;
  791. $performerProID = $performer->pro->id;
  792. $keyNumbers = [];
  793. $queryClients = $this->performer()->pro->getAccessibleClientsQuery();
  794. $pendingNotesToSign = Note
  795. ::where(function ($query) use ($performerProID) {
  796. $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_cancelled', false)->where('is_core_note', false);
  797. })
  798. ->orWhere(function ($query) use ($performerProID) {
  799. $query->where('ally_pro_id', $performerProID)->where('is_signed_by_ally', false)->where('is_cancelled', false)->where('is_core_note', false);
  800. })
  801. ->count();
  802. $keyNumbers['pendingNotesToSign'] = $pendingNotesToSign;
  803. // notes pending mcp sign (applicable to dnas only)
  804. $pendingNotesToSignMCP = Note
  805. ::where(function ($query) use ($performerProID) {
  806. $query->where('ally_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_cancelled', false)->where('is_core_note', false);
  807. })
  808. ->count();
  809. $keyNumbers['$pendingNotesToSignMCP'] = $pendingNotesToSignMCP;
  810. $pendingNotesToSignAllySigned = Note::where(function ($query) use ($performerProID) {
  811. $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);;
  812. })->count();
  813. $keyNumbers['pendingNotesToSignAllySigned'] = $pendingNotesToSignAllySigned;
  814. $signedNotesWithoutBills = Note::where(function ($query) use ($performerProID) {
  815. $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', true)->where('is_cancelled', false);
  816. })->whereDoesntHave('bills')->count();
  817. $keyNumbers['signedNotesWithoutBills'] = $signedNotesWithoutBills;
  818. // open tickets
  819. $keyNumbers['numOpenTickets'] = Ticket::where('is_open', true)
  820. ->where(function ($q) use ($performerProID) {
  821. $q->where('assigned_pro_id', $performerProID)
  822. ->orWhere('manager_pro_id', $performerProID)
  823. ->orWhere('ordering_pro_id', $performerProID)
  824. ->orWhere('initiating_pro_id', $performerProID);
  825. })
  826. ->count();
  827. // unacknowledged cancelled bills for authed pro
  828. $keyNumbers['unacknowledgedCancelledBills'] = Bill::where('hcp_pro_id', $performerProID)
  829. ->where('is_cancelled', true)
  830. ->where('is_cancellation_acknowledged', false)
  831. ->count();
  832. // unacknowledged cancelled supply orders for authed pro
  833. $keyNumbers['unacknowledgedCancelledSupplyOrders'] = SupplyOrder::where('signed_by_pro_id', $performerProID)
  834. ->where('is_cancelled', true)
  835. ->where('is_cancellation_acknowledged', false)
  836. ->count();
  837. // unsigned supply orders created by authed pro
  838. $keyNumbers['unsignedSupplyOrders'] = SupplyOrder
  839. ::where('is_cancelled', false)
  840. ->where('is_signed_by_pro', false)
  841. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session WHERE pro_id = ?)', [$performerProID])
  842. ->count();
  843. // patientsHavingBirthdayToday
  844. $queryClients = $this->performer()->pro->getAccessibleClientsQuery();
  845. $keyNumbers['patientsHavingBirthdayToday'] = $queryClients
  846. ->whereRaw('EXTRACT(DAY from dob) = ?', [date('d')])
  847. ->whereRaw('EXTRACT(MONTH from dob) = ?', [date('m')])
  848. ->count();
  849. $reimbursement = [];
  850. $reimbursement["currentBalance"] = $performer->pro->balance;
  851. $reimbursement["nextPaymentDate"] = '--';
  852. $lastPayment = ProTransaction::where('pro_id', $performerProID)->where('plus_or_minus', 'PLUS')->orderBy('created_at', 'DESC')->first();
  853. if ($lastPayment) {
  854. $reimbursement["lastPayment"] = $lastPayment->amount;
  855. $reimbursement["lastPaymentDate"] = $lastPayment->created_at;
  856. } else {
  857. $reimbursement["lastPayment"] = '--';
  858. $reimbursement["lastPaymentDate"] = '--';
  859. }
  860. //if today is < 15th, next payment is 15th, else nextPayment is
  861. $today = strtotime(date('Y-m-d'));
  862. $todayDate = date('j', $today);
  863. $todayMonth = date('m', $today);
  864. $todayYear = date('Y', $today);
  865. if ($todayDate < 15) {
  866. $nextPaymentDate = new DateTime();
  867. $nextPaymentDate->setDate($todayYear, $todayMonth, 15);
  868. $reimbursement['nextPaymentDate'] = $nextPaymentDate->format('m/d/Y');
  869. } else {
  870. $nextPaymentDate = new \DateTime();
  871. $lastDayOfMonth = date('t', $today);
  872. $nextPaymentDate->setDate($todayYear, $todayMonth, $lastDayOfMonth);
  873. $reimbursement['nextPaymentDate'] = $nextPaymentDate->format('m/d/Y');
  874. }
  875. //expectedPay
  876. $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;
  877. $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;
  878. $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;
  879. $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;
  880. $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;
  881. $totalExpectedAmount = $expectedForHcp + $expectedForCm + $expectedForRme + $expectedForRmm + $expectedForNa;
  882. $reimbursement['nextPaymentAmount'] = $totalExpectedAmount;
  883. $milliseconds = strtotime(date('Y-m-d')) . '000';
  884. // bills & claims
  885. $businessNumbers = [];
  886. // Notes with bills to resolve
  887. $businessNumbers['notesWithBillsToResolve'] = Note::where('is_cancelled', '!=', true)
  888. ->where('is_bill_closed', '!=', true)
  889. ->whereRaw('(SELECT count(id) FROM bill WHERE note_id = note.id AND is_cancelled = false AND is_verified = false) > 0')
  890. ->count();
  891. // Notes pending bill closure
  892. $businessNumbers['notesPendingBillingClosure'] = Note::where('is_cancelled', '!=', true)
  893. ->where('is_bill_closed', '!=', true)
  894. ->whereRaw('(SELECT count(id) FROM bill WHERE note_id = note.id AND (is_cancelled = true OR is_verified = true)) = 0')
  895. ->count();
  896. // incoming reports not signed
  897. $incomingReports = IncomingReport::where('hcp_pro_id', $performerProID)
  898. ->where('has_hcp_pro_signed', false)
  899. ->where('is_entry_error', false)
  900. ->orderBy('created_at', 'ASC')
  901. ->get();
  902. // erx, labs & imaging that are not closed
  903. $tickets = Ticket::where('ordering_pro_id', $performerProID)
  904. ->where('is_entry_error', false)
  905. ->where('is_open', true)
  906. ->orderBy('created_at', 'ASC')
  907. ->get();
  908. $supplyOrders = SupplyOrder::where('is_cleared_for_shipment', false)
  909. ->where('is_cancelled', false)
  910. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session where pro_id = ?)', [$performer->pro->id])
  911. ->orderBy('created_at', 'ASC')
  912. ->get();
  913. $numERx = Ticket::where('ordering_pro_id', $performerProID)
  914. ->where('category', 'erx')
  915. ->where('is_entry_error', false)
  916. ->where('is_open', true)
  917. ->count();
  918. $numLabs = Ticket::where('ordering_pro_id', $performerProID)
  919. ->where('category', 'lab')
  920. ->where('is_entry_error', false)
  921. ->where('is_open', true)
  922. ->count();
  923. $numImaging = Ticket::where('ordering_pro_id', $performerProID)
  924. ->where('category', 'imaging')
  925. ->where('is_entry_error', false)
  926. ->where('is_open', true)
  927. ->count();
  928. $numSupplyOrders = SupplyOrder::where('is_cleared_for_shipment', false)
  929. ->where('is_cancelled', false)
  930. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session where pro_id = ?)', [$performer->pro->id])
  931. ->count();
  932. $newMCPAssociations = ClientProChange
  933. ::where('new_pro_id', $performerProID)
  934. ->where('responsibility_type', 'MCP')
  935. ->whereNull('current_client_pro_change_decision_id')
  936. ->get();
  937. $newNAAssociations = ClientProChange
  938. ::where('new_pro_id', $performerProID)
  939. ->where('responsibility_type', 'DEFAULT_NA')
  940. ->whereNull('current_client_pro_change_decision_id')
  941. ->get();
  942. $proApptUpdates = AppointmentConfirmationDecision
  943. ::select('appointment_confirmation_decision.uid', 'client.name_first', 'client.name_last', 'appointment.start_time')
  944. ->rightJoin('appointment', 'appointment.id', '=', 'appointment_confirmation_decision.appointment_id')
  945. ->rightJoin('client', 'client.id', '=', 'appointment.client_id')
  946. ->where('appointment_confirmation_decision.was_acknowledged_by_appointment_pro', false)
  947. ->where('appointment.status', '!=', 'CREATED')
  948. ->where('appointment.status', '!=', 'COMPLETED')
  949. ->where('appointment.status', '!=', 'ABANDONED')
  950. ->where('appointment.pro_id', $performerProID)
  951. ->where('client.mcp_pro_id', $performerProID)
  952. ->orderBy('appointment.start_time', 'DESC')
  953. ->get();
  954. $naApptUpdates = AppointmentConfirmationDecision
  955. ::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')
  956. ->rightJoin('appointment', 'appointment.id', '=', 'appointment_confirmation_decision.appointment_id')
  957. ->rightJoin('client', 'client.id', '=', 'appointment.client_id')
  958. ->rightJoin('pro', 'pro.id', '=', 'appointment.pro_id')
  959. ->where('appointment_confirmation_decision.was_acknowledged_by_client_default_na', false)
  960. ->where('appointment.status', '!=', 'CREATED')
  961. ->where('appointment.status', '!=', 'COMPLETED')
  962. ->where('appointment.status', '!=', 'ABANDONED')
  963. ->where('client.default_na_pro_id', $performerProID)
  964. ->orderBy('appointment.start_time', 'DESC')
  965. ->get();
  966. // $naApptUpdates = AppointmentConfirmationDecision
  967. // ::join('appointment', 'appointment.id', '=', 'appointment_confirmation_decision.appointment_id')
  968. // ->join('client', 'client.id', '=', 'appointment.client_id')
  969. // ->where('client.default_na_pro_id', $performerProID)
  970. // ->where('appointment_confirmation_decision.was_acknowledged_by_client_default_na', false)
  971. // ->orderBy('appointment.start_time DESC')
  972. // ->get();
  973. // unstamped client memos
  974. // for mcp
  975. $mcpClientMemos = DB::select(
  976. DB::raw("
  977. SELECT c.uid as client_uid, c.name_first, c.name_last,
  978. cm.uid, cm.content, cm.created_at
  979. FROM client c join client_memo cm on c.id = cm.client_id
  980. WHERE
  981. c.mcp_pro_id = {$performerProID} AND
  982. cm.mcp_stamp_id IS NULL
  983. ORDER BY cm.created_at DESC
  984. ")
  985. );
  986. // for na
  987. $naClientMemos = DB::select(
  988. DB::raw("
  989. SELECT c.uid as client_uid, c.name_first, c.name_last,
  990. cm.uid, cm.content, cm.created_at
  991. FROM client c join client_memo cm on c.id = cm.client_id
  992. WHERE
  993. c.default_na_pro_id = {$performerProID} AND
  994. cm.default_na_stamp_id IS NULL
  995. ORDER BY cm.created_at DESC
  996. ")
  997. );
  998. $keyNumbers['rmBillsToSign'] = Bill
  999. ::where('is_cancelled', false)
  1000. ->where('cm_or_rm', 'RM')
  1001. ->where(function ($q) use ($performerProID) {
  1002. $q
  1003. ->where(function ($q2) use ($performerProID) {
  1004. $q2->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false);
  1005. })
  1006. ->orWhere(function ($q2) use ($performerProID) {
  1007. $q2->where('rme_pro_id', $performerProID)->where('is_signed_by_rme', false);
  1008. })
  1009. ->orWhere(function ($q2) use ($performerProID) {
  1010. $q2->where('rmm_pro_id', $performerProID)->where('is_signed_by_rmm', false);
  1011. })
  1012. ->orWhere(function ($q2) use ($performerProID) {
  1013. $q2->where('generic_pro_id', $performerProID)->where('is_signed_by_generic_pro', false);
  1014. });
  1015. })
  1016. ->count();
  1017. $count = DB::select(
  1018. DB::raw(
  1019. "
  1020. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  1021. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  1022. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  1023. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  1024. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  1025. AND (care_month.number_of_days_with_remote_measurements < 16 OR care_month.number_of_days_with_remote_measurements IS NULL)
  1026. "
  1027. )
  1028. );
  1029. $keyNumbers['rmPatientsWithLT16MD'] = $count[0]->cnt;
  1030. $count = DB::select(
  1031. DB::raw(
  1032. "
  1033. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  1034. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  1035. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  1036. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  1037. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  1038. AND (care_month.number_of_days_with_remote_measurements >= 16 AND care_month.number_of_days_with_remote_measurements IS NOT NULL)
  1039. "
  1040. )
  1041. );
  1042. $keyNumbers['rmPatientsWithGTE16MD'] = $count[0]->cnt;
  1043. $count = DB::select(
  1044. DB::raw(
  1045. "
  1046. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  1047. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  1048. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  1049. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  1050. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  1051. 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)
  1052. "
  1053. )
  1054. );
  1055. $keyNumbers['rmPatientsWithWhomCommDone'] = $count[0]->cnt;
  1056. $count = DB::select(
  1057. DB::raw(
  1058. "
  1059. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  1060. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  1061. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  1062. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  1063. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  1064. 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)
  1065. "
  1066. )
  1067. );
  1068. $keyNumbers['rmPatientsWithWhomCommNotDone'] = $count[0]->cnt;
  1069. // num measurements that need stamping
  1070. $keyNumbers['measurementsToBeStamped'] = $this->performer()->pro->getUnstampedMeasurementsFromCurrentMonth(true, null, null);
  1071. if($performer->pro->pro_type === 'ADMIN') {
  1072. // patients without coverage information
  1073. $keyNumbers['patientsWithoutCoverageInformation'] = DB::select(DB::raw("
  1074. SELECT count(DISTINCT (cl.id)) as cnt
  1075. FROM client cl
  1076. WHERE cl.shadow_pro_id IS NULL AND cl.latest_client_primary_coverage_id IS NULL -- no coverage record"
  1077. ))[0]->cnt;
  1078. // patients pending coverage verification
  1079. $keyNumbers['patientsPendingCoverageVerification'] = DB::select(DB::raw("
  1080. SELECT count(DISTINCT (cl.id)) as cnt
  1081. FROM client cl
  1082. LEFT JOIN client_primary_coverage cpc ON cl.latest_client_primary_coverage_id = cpc.id
  1083. WHERE cl.shadow_pro_id IS NULL
  1084. AND (cl.latest_client_primary_coverage_id IS NOT NULL -- coverage exists, but status is null or unknown
  1085. AND (
  1086. (cpc.plan_type = 'MEDICARE' AND (cpc.is_partbprimary = 'UNKNOWN' OR cpc.is_partbprimary IS NULL))
  1087. OR
  1088. (cpc.plan_type != 'MEDICARE' AND
  1089. (cpc.manual_determination_category = 'UNKNOWN' OR cpc.manual_determination_category IS NULL))
  1090. ))"
  1091. ))[0]->cnt;
  1092. }
  1093. return view('app/dashboard-admin', compact('keyNumbers', 'reimbursement', 'milliseconds',
  1094. 'businessNumbers',
  1095. 'incomingReports', 'tickets', 'supplyOrders',
  1096. 'numERx', 'numLabs', 'numImaging', 'numSupplyOrders',
  1097. 'newMCPAssociations', 'newNAAssociations',
  1098. 'mcpClientMemos', 'naClientMemos',
  1099. 'proApptUpdates', 'naApptUpdates'));
  1100. }
  1101. public function dashboard(Request $request)
  1102. {
  1103. $performer = $this->performer();
  1104. $pro = $performer->pro;
  1105. if($pro->is_enrolled_as_mcp){
  1106. return $this->dashboard_MCP($request);
  1107. }elseif($pro->pro_type === 'ADMIN'){
  1108. return $this->dashboard_ADMIN($request);
  1109. }else{
  1110. return $this->dashboard_DNA($request);
  1111. }
  1112. }
  1113. public function dashboardMeasurementsTab(Request $request, $page = 1) {
  1114. $performer = $this->performer();
  1115. $myClientIDs = [];
  1116. if ($performer->pro->pro_type != 'ADMIN') {
  1117. $myClientIDs = $this->getMyClientIds();
  1118. $myClientIDs = implode(", ", $myClientIDs);
  1119. }
  1120. $ifNotAdmin = " AND (
  1121. client.mcp_pro_id = {$performer->pro->id}
  1122. OR client.rmm_pro_id = {$performer->pro->id}
  1123. OR client.rme_pro_id = {$performer->pro->id}
  1124. OR client.physician_pro_id = {$performer->pro->id}
  1125. OR client.id in (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = {$performer->pro->id})
  1126. OR client.id in (SELECT client_id FROM appointment WHERE status NOT IN ('CANCELLED') AND pro_id = {$performer->pro->id})
  1127. )";
  1128. $numMeasurements = DB::select(
  1129. DB::raw(
  1130. "
  1131. SELECT count(measurement.id) as cnt
  1132. FROM measurement
  1133. join client on measurement.client_id = client.id
  1134. WHERE measurement.label NOT IN ('SBP', 'DBP')
  1135. AND (measurement.is_cellular_zero = FALSE or measurement.is_cellular_zero IS NULL)
  1136. AND measurement.is_removed IS FALSE
  1137. AND measurement.has_been_stamped_by_mcp IS FALSE
  1138. AND measurement.ts IS NOT NULL
  1139. AND measurement.client_bdt_measurement_id IS NOT NULL
  1140. AND (measurement.status IS NULL OR (measurement.status <> 'ACK' AND measurement.status <> 'INVALID_ACK'))
  1141. AND EXTRACT(MONTH from measurement.created_at) = EXTRACT(MONTH from NOW())
  1142. AND EXTRACT(YEAR from measurement.created_at) = EXTRACT(YEAR from NOW())
  1143. " .
  1144. (
  1145. $performer->pro->pro_type != 'ADMIN' ? $ifNotAdmin : ''
  1146. )
  1147. )
  1148. );
  1149. $numMeasurements = $numMeasurements[0]->cnt;
  1150. $measurements = DB::select(
  1151. DB::raw(
  1152. "
  1153. SELECT measurement.uid as uid,
  1154. care_month.uid as care_month_uid,
  1155. care_month.start_date as care_month_start_date,
  1156. measurement.label,
  1157. measurement.value,
  1158. measurement.sbp_mm_hg,
  1159. measurement.dbp_mm_hg,
  1160. measurement.numeric_value,
  1161. measurement.value_pulse,
  1162. measurement.value_irregular,
  1163. measurement.ts,
  1164. client.id as client_id,
  1165. client.mcp_pro_id,
  1166. client.default_na_pro_id,
  1167. client.rmm_pro_id,
  1168. client.rme_pro_id,
  1169. client.uid as client_uid,
  1170. client.name_last,
  1171. client.name_first,
  1172. care_month.rm_total_time_in_seconds
  1173. FROM measurement
  1174. join client on measurement.client_id = client.id
  1175. join care_month on client.id = care_month.client_id
  1176. WHERE measurement.label NOT IN ('SBP', 'DBP')
  1177. AND (measurement.is_cellular_zero = FALSE or measurement.is_cellular_zero IS NULL)
  1178. AND measurement.is_removed IS FALSE
  1179. AND measurement.has_been_stamped_by_mcp IS FALSE
  1180. AND measurement.ts IS NOT NULL
  1181. AND measurement.client_bdt_measurement_id IS NOT NULL
  1182. AND (measurement.status IS NULL OR (measurement.status <> 'ACK' AND measurement.status <> 'INVALID_ACK'))
  1183. AND EXTRACT(MONTH from measurement.created_at) = EXTRACT(MONTH from NOW())
  1184. AND EXTRACT(YEAR from measurement.created_at) = EXTRACT(YEAR from NOW())
  1185. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from NOW())
  1186. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from NOW())
  1187. " .
  1188. (
  1189. $performer->pro->pro_type != 'ADMIN' ? $ifNotAdmin : ''
  1190. )
  1191. ) .
  1192. " ORDER BY measurement.ts DESC LIMIT 20 OFFSET " . (($page - 1) * 20)
  1193. );
  1194. return view('app.dashboard.measurements', compact('numMeasurements', 'measurements', 'page'));
  1195. }
  1196. public function dashboardAppointmentDates(Request $request, $from, $to) {
  1197. $performer = $this->performer();
  1198. $performerProID = $performer->pro->id;
  1199. $isAdmin = ($performer->pro->pro_type === 'ADMIN');
  1200. $results = DB::table('appointment')->select('raw_date')->distinct()->where("start_time", '>=', $from)->where("start_time", '<=', $to.' 23:59:00+00');
  1201. if(!$isAdmin) {
  1202. $results = $results->where("pro_id", $performerProID);
  1203. }
  1204. $results = $results->get();
  1205. $dates = [];
  1206. foreach ($results as $result) {
  1207. // $dates[] = strtotime($result->raw_date) . '000';
  1208. $dates[] = $result->raw_date;
  1209. }
  1210. // foreach ($results as $result) {
  1211. // $results->dateYMD = date('Y-m-d', strtotime($result->raw_date));
  1212. // }
  1213. return json_encode($dates);
  1214. }
  1215. public function dashboardAppointments(Request $request, $from, $to) {
  1216. $performer = $this->performer();
  1217. $performerProID = $performer->pro->id;
  1218. $isAdmin = ($performer->pro->pro_type === 'ADMIN');
  1219. // $appointments = Appointment::where("start_time", '>=', $from)->where("start_time", '<=', $to.' 23:59:00+00');
  1220. $appointments = Appointment::where("raw_date", '=', $from);
  1221. if(!$isAdmin) {
  1222. $appointments = $appointments->where("pro_id", $performerProID);
  1223. }
  1224. $appointments = $appointments
  1225. // ->whereRaw('status NOT IN (\'CANCELLED\', \'COMPLETED\')')
  1226. ->orderBy('start_time', 'asc')
  1227. ->get();
  1228. foreach ($appointments as $appointment) {
  1229. $date = explode(" ", $appointment->start_time)[0];
  1230. $appointment->milliseconds = strtotime($date) . '000';
  1231. $appointment->newStatus = $appointment->status;
  1232. $appointment->dateYMD = date('Y-m-d', strtotime($appointment->raw_date));
  1233. $appointment->clientName = $appointment->client->displayName();
  1234. $appointment->clientInitials = substr($appointment->client->name_first, 0, 1) . substr($appointment->client->name_last, 0, 1);
  1235. $appointment->isClientShadowOfPro = $appointment->client->shadow_pro_id ? true : false;
  1236. $appointment->proInitials = substr($appointment->pro->name_first, 0, 1) . substr($appointment->pro->name_last, 0, 1);
  1237. $appointment->friendlyStartTime = friendly_time($appointment->raw_start_time);
  1238. $appointment->friendlyEndTime = friendly_time($appointment->raw_end_time);
  1239. $appointment->clientSummary = friendly_date_time($appointment->client->dob, false) . ' (' .
  1240. $appointment->client->age_in_years . ' y.o' .
  1241. ($appointment->client->sex ? ' ' . $appointment->client->sex : '') .
  1242. ')';
  1243. $appointment->clientAge = $appointment->client->age_in_years;
  1244. $appointment->clientSex = $appointment->client->sex;
  1245. $appointment->started = false;
  1246. $appointment->inHowManyHours = date_diff(date_create('now'), date_create($appointment->start_time), false)
  1247. ->format('%R%h h, %i m');
  1248. if ($appointment->inHowManyHours[0] === '-') {
  1249. $appointment->inHowManyHours = substr($appointment->inHowManyHours, 1) . ' ago';
  1250. $appointment->started = true;
  1251. } else {
  1252. $appointment->inHowManyHours = 'Appt. in ' . substr($appointment->inHowManyHours, 1);
  1253. }
  1254. $appointment->clientUid = $appointment->client->uid;
  1255. $appointment->proUid = $appointment->pro->uid;
  1256. $appointment->proName = $appointment->pro->displayName();
  1257. // insurance information
  1258. $appointment->coverage = $appointment->client->getPrimaryCoverageStatus();
  1259. unset($appointment->client);
  1260. unset($appointment->pro);
  1261. unset($appointment->detail_json);
  1262. }
  1263. return json_encode($appointments);
  1264. }
  1265. public function dashboardAppointmentsDisplay(Request $request, $from, $to) {
  1266. $performer = $this->performer();
  1267. $performerProID = $performer->pro->id;
  1268. $isAdmin = ($performer->pro->pro_type === 'ADMIN');
  1269. // $appointments = Appointment::where("start_time", '>=', $from)->where("start_time", '<=', $to.' 23:59:00+00');
  1270. $appointments = Appointment::where("raw_date", '=', $from);
  1271. if(!$isAdmin) {
  1272. $appointments = $appointments->where("pro_id", $performerProID);
  1273. }
  1274. $appointments = $appointments
  1275. ->orderBy('start_time', 'asc')
  1276. ->get();
  1277. foreach ($appointments as $appointment) {
  1278. $date = explode(" ", $appointment->start_time)[0];
  1279. $appointment->milliseconds = strtotime($date) . '000';
  1280. $appointment->newStatus = $appointment->status;
  1281. $appointment->dateYMD = date('Y-m-d', strtotime($appointment->raw_date));
  1282. $appointment->clientName = $appointment->client->displayName();
  1283. $appointment->clientInitials = substr($appointment->client->name_first, 0, 1) . substr($appointment->client->name_last, 0, 1);
  1284. $appointment->isClientShadowOfPro = $appointment->client->shadow_pro_id ? true : false;
  1285. $appointment->proInitials = substr($appointment->pro->name_first, 0, 1) . substr($appointment->pro->name_last, 0, 1);
  1286. $appointment->friendlyStartTime = friendly_time($appointment->raw_start_time);
  1287. $appointment->friendlyEndTime = friendly_time($appointment->raw_end_time);
  1288. $appointment->clientSummary = friendly_date_time($appointment->client->dob, false) . ' (' .
  1289. $appointment->client->age_in_years . ' y.o' .
  1290. ($appointment->client->sex ? ' ' . $appointment->client->sex : '') .
  1291. ')';
  1292. $appointment->clientAge = $appointment->client->age_in_years;
  1293. $appointment->clientSex = $appointment->client->sex;
  1294. $appointment->started = false;
  1295. $appointment->inHowManyHours = date_diff(date_create('now'), date_create($appointment->start_time), false)
  1296. ->format('%R%h h, %i m');
  1297. if ($appointment->inHowManyHours[0] === '-') {
  1298. $appointment->inHowManyHours = substr($appointment->inHowManyHours, 1) . ' ago';
  1299. $appointment->started = true;
  1300. } else {
  1301. $appointment->inHowManyHours = 'Appt. in ' . substr($appointment->inHowManyHours, 1);
  1302. }
  1303. $appointment->clientUid = $appointment->client->uid;
  1304. $appointment->proUid = $appointment->pro->uid;
  1305. $appointment->proName = $appointment->pro->displayName();
  1306. // insurance information
  1307. $appointment->coverage = $appointment->client->getPrimaryCoverageStatus();
  1308. // bg color
  1309. $appointment->bgColor = 'bg-white';
  1310. if($appointment->status === 'COMPLETED') {
  1311. $appointment->bgColor = 'event-bg-green';
  1312. }
  1313. else if($appointment->status === 'CANCELLED') {
  1314. $appointment->bgColor = 'event-bg-gray';
  1315. }
  1316. unset($appointment->client);
  1317. unset($appointment->pro);
  1318. unset($appointment->detail_json);
  1319. }
  1320. return view('app.mcp.dashboard.appointments-list', compact('appointments', 'from', 'to'));
  1321. }
  1322. public function dashboardMeasurements(Request $request, $filter) {
  1323. $measurements = $this->performer()->pro->getMeasurements($filter === 'NEED_ACK');
  1324. return json_encode($measurements);
  1325. }
  1326. public function patients(Request $request, $filter = '')
  1327. {
  1328. $performer = $this->performer();
  1329. $query = $performer->pro->getAccessibleClientsQuery();
  1330. $q = trim($request->input('q'));
  1331. if(!empty($q)) {
  1332. $query = $query->where(function ($query) use ($q) {
  1333. $query->where('name_first', 'ILIKE', "%$q%")
  1334. ->orWhere('name_last', 'ILIKE', "%$q%")
  1335. ->orWhere('email_address', 'ILIKE', "%$q%")
  1336. ->orWhere('tags', 'ILIKE', "%$q%");
  1337. });
  1338. }
  1339. switch ($filter) {
  1340. case 'not-yet-seen':
  1341. $query = $query
  1342. ->where(function ($query) use ($performer) {
  1343. $query
  1344. ->where(function ($query) use ($performer) { // own patient and primary OB visit pending
  1345. $query->where('mcp_pro_id', $performer->pro->id)
  1346. ->where('has_mcp_done_onboarding_visit', '<>', 'YES');
  1347. })
  1348. ->orWhere(function ($query) use ($performer) { // mcp of any client program and program OB pending
  1349. $query->select(DB::raw('COUNT(id)'))
  1350. ->from('client_program')
  1351. ->whereColumn('client_id', 'client.id')
  1352. ->where('mcp_pro_id', $performer->pro->id)
  1353. ->where('has_mcp_done_onboarding_visit', '<>', 'YES');
  1354. }, '>=', 1);
  1355. });
  1356. break;
  1357. case 'having-birthday-today':
  1358. $query = $query
  1359. ->whereRaw('EXTRACT(DAY from dob) = ?', [date('d')])
  1360. ->whereRaw('EXTRACT(MONTH from dob) = ?', [date('m')]);
  1361. break;
  1362. // more cases can be added as needed
  1363. default:
  1364. break;
  1365. }
  1366. $patients = $query->orderBy('id', 'desc')->paginate(50);
  1367. // patient acquisition chart (admin only)
  1368. $patientAcquisitionData = null;
  1369. if($performer->pro->pro_type === 'ADMIN') {
  1370. $startDate = date_sub(date_create(), date_interval_create_from_date_string("1 month"));
  1371. $startDate = date_format($startDate, "Y-m-d");
  1372. $patientAcquisitionData = DB::select(DB::raw(
  1373. "SELECT count(id) as count, DATE(created_at at time zone 'utc' at time zone 'est') as date " .
  1374. "FROM client " .
  1375. "WHERE shadow_pro_id IS NULL " .
  1376. "GROUP BY DATE(created_at at time zone 'utc' at time zone 'est') " .
  1377. "ORDER BY DATE(created_at at time zone 'utc' at time zone 'est') DESC " .
  1378. "LIMIT 30"));
  1379. }
  1380. return view('app/patients', compact('patients', 'filter', 'patientAcquisitionData'));
  1381. }
  1382. public function patientsSuggest(Request $request)
  1383. {
  1384. $pro = $this->pro;
  1385. $term = $request->input('term') ? trim($request->input('term')) : '';
  1386. $originalTerm = $term;
  1387. if (empty($term)) return '';
  1388. // if multiple words in query, check for all (max 2)
  1389. $term2 = '';
  1390. if(strpos($term, ' ') !== FALSE) {
  1391. $terms = explode(' ', $term);
  1392. $term = trim($terms[0]);
  1393. $term2 = trim($terms[1]);
  1394. }
  1395. $phoneNumberTerm = preg_replace("/[^0-9]/", "", $originalTerm );
  1396. if($phoneNumberTerm == ""){ //to avoid search with blank string
  1397. $phoneNumberTerm = $term;
  1398. }
  1399. $clientQuery= Client::whereNull('shadow_pro_id')
  1400. ->where(function ($q) use ($term, $phoneNumberTerm) {
  1401. $q->where('name_first', 'ILIKE', '%' . $term . '%')
  1402. ->orWhere('name_last', 'ILIKE', '%' . $term . '%')
  1403. ->orWhere('cell_number', 'ILIKE', '%' . $phoneNumberTerm . '%')
  1404. ->orWhere('phone_home', 'ILIKE', '%' . $phoneNumberTerm . '%');
  1405. });
  1406. if(!empty($term2)) {
  1407. $clientQuery = $clientQuery->where(function ($q) use ($term2, $phoneNumberTerm) {
  1408. $q->where('name_first', 'ILIKE', '%' . $term2 . '%')
  1409. ->orWhere('name_last', 'ILIKE', '%' . $term2 . '%')
  1410. ->orWhere('cell_number', 'ILIKE', '%' . $phoneNumberTerm . '%')
  1411. ->orWhere('phone_home', 'ILIKE', '%' . $phoneNumberTerm . '%');
  1412. });
  1413. }
  1414. if(!($pro->pro_type === 'ADMIN' && $pro->can_see_any_client_via_search)) {
  1415. $clientQuery->where(function ($q) use ($pro) {
  1416. if($pro->pro_type === 'ADMIN') {
  1417. $q->whereIn('id', $pro->getMyClientIds(true))->orWhereNull('mcp_pro_id');
  1418. }
  1419. else {
  1420. $q->whereIn('id', $pro->getMyClientIds(true));
  1421. }
  1422. });
  1423. }
  1424. $clients = $clientQuery->get();
  1425. return view('app/patient-suggest', compact('clients'));
  1426. }
  1427. public function pharmacySuggest(Request $request)
  1428. {
  1429. $term = $request->input('term') ? trim($request->input('term')) : '';
  1430. if (empty($term)) return '';
  1431. $term = strtolower($term);
  1432. $pharmacies = Facility::where('facility_type', 'Pharmacy')
  1433. ->where(function ($q) use ($term) {
  1434. $q->orWhereRaw('LOWER(name::text) LIKE ?', ['%' . $term . '%'])
  1435. ->orWhereRaw('LOWER(address_line1::text) LIKE ?', ['%' . $term . '%'])
  1436. ->orWhereRaw('LOWER(address_line2::text) LIKE ?', ['%' . $term . '%'])
  1437. ->orWhereRaw('LOWER(address_city::text) LIKE ?', ['%' . $term . '%'])
  1438. ->orWhereRaw('LOWER(address_state::text) LIKE ?', ['%' . $term . '%'])
  1439. ->orWhereRaw('LOWER(phone::text) LIKE ?', ['%' . $term . '%'])
  1440. ->orWhereRaw('LOWER(address_zip::text) LIKE ?', ['%' . $term . '%']);
  1441. });
  1442. if($request->input('city')) {
  1443. $pharmacies = $pharmacies->whereRaw('LOWER(address_city::text) LIKE ?', ['%' . strtolower($request->input('city')) . '%']);
  1444. }
  1445. if($request->input('state')) {
  1446. $pharmacies = $pharmacies->whereRaw('LOWER(address_state::text) LIKE ?', ['%' . strtolower($request->input('state')) . '%']);
  1447. }
  1448. if($request->input('zip')) {
  1449. $pharmacies = $pharmacies->whereRaw('LOWER(address_zip::text) LIKE ?', ['%' . strtolower($request->input('zip')) . '%']);
  1450. }
  1451. $pharmacies = $pharmacies
  1452. ->orderBy('name', 'asc')
  1453. ->orderBy('address_line1', 'asc')
  1454. ->orderBy('address_city', 'asc')
  1455. ->orderBy('address_state', 'asc')
  1456. ->get();
  1457. return view('app/pharmacy-suggest', compact('pharmacies'));
  1458. }
  1459. public function facilitySuggestJSON(Request $request)
  1460. {
  1461. $term = $request->input('term') ? trim($request->input('term')) : '';
  1462. if (empty($term)) return '';
  1463. $terms = explode(' ', $term);
  1464. $terms = array_filter($terms, function($_x) {
  1465. return !!trim($_x);
  1466. });
  1467. $whereCondition = [];
  1468. $whereParams = [];
  1469. for ($i = 0; $i < count($terms); $i++) {
  1470. $whereCondition[] = "(name ILIKE :term{$i} OR address_city ILIKE :term{$i} OR address_state ILIKE :term{$i} OR address_zip ILIKE :term{$i})";
  1471. $whereParams["term{$i}"] = '%' . $terms[$i] . '%';
  1472. }
  1473. $whereCondition = implode(" AND ", $whereCondition);
  1474. $matches = DB::select(
  1475. "SELECT (name || ' ' || address_city || ' ' || address_state || ' ' || address_zip) as text,
  1476. address_line1 as text2,
  1477. name, address_city as city, address_state as state, address_zip as zip, phone, fax FROM facility
  1478. WHERE {$whereCondition} ORDER BY name", $whereParams);
  1479. return json_encode([
  1480. "success" => true,
  1481. "data" => $matches
  1482. ]);
  1483. }
  1484. public function proSuggest(Request $request) {
  1485. $term = $request->input('term') ? trim($request->input('term')) : '';
  1486. if (empty($term)) return '';
  1487. $term = strtolower($term);
  1488. $pros = Pro::where(function ($q) use ($term) {
  1489. $q->orWhereRaw('LOWER(name_first::text) LIKE ?', ['%' . $term . '%'])
  1490. ->orWhereRaw('LOWER(name_last::text) LIKE ?', ['%' . $term . '%'])
  1491. ->orWhereRaw('cell_number LIKE ?', ['%' . $term . '%']);
  1492. });
  1493. $type = $request->input('type') ? trim($request->input('type')) : '';
  1494. if(!!$type) {
  1495. switch(strtolower($type)) {
  1496. case 'hcp':
  1497. $pros->where('is_hcp', true);
  1498. break;
  1499. case 'default-na': // TODO: fix condition for NA
  1500. $pros->where('is_hcp', false)->where('pro_type', '!=', 'ADMIN');
  1501. break;
  1502. case 'admin':
  1503. $pros->where('pro_type', 'ADMIN');
  1504. break;
  1505. case 'non-admin':
  1506. $pros->where('pro_type', '!=', 'ADMIN');
  1507. break;
  1508. }
  1509. }
  1510. if($this->performer->pro && $this->performer->pro->pro_type != 'ADMIN'){
  1511. $accessiblePros = ProProAccess::where('owner_pro_id', $this->performer->pro->id);
  1512. $accessibleProIds = [];
  1513. foreach($accessiblePros as $accessiblePro){
  1514. $accessibleProIds[] = $accessiblePro->id;
  1515. }
  1516. $accessibleProIds[] = $this->performer->pro->id;
  1517. // for dna, add pros accessible via pro teams
  1518. if($this->performer->pro->isDefaultNA()) {
  1519. $teams = $this->performer->pro->teamsWhereAssistant;
  1520. foreach ($teams as $team) {
  1521. if(!in_array($team->mcp_pro_id, $accessibleProIds)) {
  1522. $accessibleProIds[] = $team->mcp_pro_id;
  1523. }
  1524. }
  1525. }
  1526. $pros->whereIn('id', $accessibleProIds);
  1527. }
  1528. $suggestedPros = $pros->orderBy('name_last')->orderBy('name_first')->get();
  1529. // for calendar select2
  1530. if($request->input('json')) {
  1531. $jsonPros = $suggestedPros->map(function($_pro) {
  1532. return [
  1533. "uid" => $_pro->uid,
  1534. "id" => $_pro->id,
  1535. "text" => $_pro->displayName(),
  1536. "initials" => $_pro->initials(),
  1537. ];
  1538. });
  1539. return json_encode([
  1540. "results" => $jsonPros
  1541. ]);
  1542. }
  1543. return view('app/pro-suggest', compact('suggestedPros'));
  1544. }
  1545. public function canAccessPatient(Request $request, $uid) {
  1546. return json_encode([
  1547. "success" => true,
  1548. "data" => $this->performer->pro->canAccess($uid)
  1549. ]);
  1550. }
  1551. public function proDisplayName(Request $request, Pro $pro) {
  1552. return $pro ? $pro->displayName() : '';
  1553. }
  1554. public function unmappedSMS(Request $request, $filter = '')
  1555. {
  1556. $proID = $this->performer()->pro->id;
  1557. if ($this->performer()->pro->pro_type === 'ADMIN') {
  1558. $query = Client::where('id', '>', 0);
  1559. } else {
  1560. $query = Client::where(function ($q) use ($proID) {
  1561. $q->where('mcp_pro_id', $proID)
  1562. ->orWhere('cm_pro_id', $proID)
  1563. ->orWhere('rmm_pro_id', $proID)
  1564. ->orWhere('rme_pro_id', $proID)
  1565. ->orWhereRaw('id IN (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = ?)', [$proID]);
  1566. });
  1567. }
  1568. $patients = $query->orderBy('name_last', 'asc')->orderBy('name_first', 'asc')->get();
  1569. $unmappedSMS = ClientSMS::where('client_id', null)->where('incoming_or_outgoing', 'INCOMING')->paginate(20);
  1570. return view('app/unmapped-sms', compact('unmappedSMS', 'patients'));
  1571. }
  1572. public function newPatient(Request $request)
  1573. {
  1574. $mbPayers = MBPayer::all();
  1575. return view('app/new-patient', compact('mbPayers'));
  1576. }
  1577. public function newNonMcnPatient(Request $request)
  1578. {
  1579. $mbPayers = MBPayer::all();
  1580. return view('app/new-non-mcn-patient', compact('mbPayers'));
  1581. }
  1582. public function mc(Request $request, $fragment = "")
  1583. {
  1584. $page = "/";
  1585. if ($fragment) {
  1586. $page = '/' . $fragment;
  1587. }
  1588. return view('app/mc', compact('page'));
  1589. }
  1590. public function blank(Request $request)
  1591. {
  1592. return view('app/blank');
  1593. }
  1594. public function noteTemplateSet(Request $request, $section, $template)
  1595. {
  1596. return view('app/patient/note/_template', [
  1597. "sectionInternalName" => $section,
  1598. "templateName" => $template
  1599. ]);
  1600. }
  1601. public function noteExamTemplateSet(Request $request, $exam, $template)
  1602. {
  1603. return view('app/patient/note/_template-exam', [
  1604. "exam" => $exam,
  1605. "sectionInternalName" => 'exam-' . $exam . '-detail',
  1606. "templateName" => $template
  1607. ]);
  1608. }
  1609. public function logInAs(Request $request)
  1610. {
  1611. if($this->pro->pro_type != 'ADMIN'){
  1612. return redirect()->to(route('dashboard'));
  1613. }
  1614. // dummy condition to get the chain-ability going
  1615. $pros = Pro::where('id', '>', 0);
  1616. if($request->input('q')) {
  1617. $nameQuery = '%' . $request->input('q') . '%';
  1618. $pros = $pros->where(function ($query) use ($nameQuery) {
  1619. $query->where('name_first', 'ILIKE', $nameQuery)
  1620. ->orWhere('name_last', 'ILIKE', $nameQuery)
  1621. ->orWhere('email_address', 'ILIKE', $nameQuery)
  1622. ->orWhere('cell_number', 'ILIKE', $nameQuery);
  1623. });
  1624. }
  1625. if($request->input('sort') && $request->input('dir')) {
  1626. $pros = $pros->orderBy($request->input('sort'), $request->input('dir'));
  1627. }
  1628. else {
  1629. $pros = $pros->orderBy('name_last', 'asc');
  1630. }
  1631. $pros = $pros->paginate(20);
  1632. return view('app/log-in-as', ['logInAsPros' => $pros]);
  1633. }
  1634. public function processLogInAs(Request $request)
  1635. {
  1636. $api = new Backend();
  1637. try {
  1638. $apiResponse = $api->post('session/proLogInAs', [
  1639. 'proUid' => $request->post('proUid')
  1640. ],
  1641. [
  1642. 'sessionKey'=>$this->performer()->session_key
  1643. ]);
  1644. $data = json_decode($apiResponse->getContents());
  1645. if (!property_exists($data, 'success') || !$data->success) {
  1646. return redirect()->to(route('log-in-as'))->with('message', $data->message)
  1647. ->withInput($request->input());
  1648. }
  1649. Cookie::queue('sessionKey', $data->data->sessionKey);
  1650. return redirect('/mc');
  1651. } catch (\Exception $e) {
  1652. return redirect()->to(route('log-in-as'))
  1653. ->with('message', 'Unable to process your request at the moment. Please try again later.')
  1654. ->withInput($request->input());
  1655. }
  1656. }
  1657. public function backToAdminPro(Request $request){
  1658. $adminPerformerId = $this->performer->logged_in_as_pro_from_admin_pro_app_session_id;
  1659. $adminPerformer = AppSession::where('id', $adminPerformerId)->first();
  1660. $url = "/session/pro_log_in_with_session_key/".$adminPerformer->session_key;
  1661. $api = new Backend();
  1662. try {
  1663. $apiResponse = $api->post($url, []);
  1664. $data = json_decode($apiResponse->getContents());
  1665. if (!property_exists($data, 'success') || !$data->success) {
  1666. return redirect()->to(route('logout'));
  1667. }
  1668. Cookie::queue('sessionKey', $data->data->sessionKey);
  1669. return redirect(route('dashboard'));
  1670. } catch (\Exception $e) {
  1671. return redirect(route('dashboard'));
  1672. }
  1673. }
  1674. public function getTicket(Request $request, Ticket $ticket) {
  1675. $ticket->data = json_decode($ticket->data);
  1676. // $ticket->created_at = friendly_date_time($ticket->created_at);
  1677. $ticket->assignedPro;
  1678. $ticket->managerPro;
  1679. $ticket->orderingPro;
  1680. $ticket->initiatingPro;
  1681. return json_encode($ticket);
  1682. }
  1683. public function genericBill(Request $request, $entityType, $entityUid) {
  1684. $patient = null;
  1685. if ($entityType && $entityUid) {
  1686. try {
  1687. $entityClass = "\\App\\Models\\" . $entityType;
  1688. $entity = $entityClass::where('uid', $entityUid)->first();
  1689. if ($entity->client) {
  1690. $patient = $entity->client;
  1691. }
  1692. } catch (\Exception $e) {
  1693. }
  1694. }
  1695. return view('app.generic-bills.inline', ['class' => 'p-3 border-top mt-3', 'entityType' => $entityType, 'entityUid' => $entityUid, 'patient' => $patient]);
  1696. }
  1697. }