HomeController.php 97 KB

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