HomeController.php 76 KB

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