12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664 |
- <?php
- namespace App\Http\Controllers;
- use App\Lib\Backend;
- use App\Models\Appointment;
- use App\Models\AppointmentConfirmationDecision;
- use App\Models\AppSession;
- use App\Models\CareMonth;
- use App\Models\ClientMemo;
- use App\Models\ClientProChange;
- use App\Models\ClientSMS;
- use App\Models\Facility;
- use App\Models\IncomingReport;
- use App\Models\MBPayer;
- use App\Models\ProProAccess;
- use App\Models\SupplyOrder;
- use App\Models\Ticket;
- use DateTime;
- use App\Models\Client;
- use App\Models\Bill;
- use App\Models\Measurement;
- use App\Models\Note;
- use App\Models\Pro;
- use App\Models\ProTransaction;
- use GuzzleHttp\Cookie\CookieJar;
- use Illuminate\Http\Request;
- use Illuminate\Support\Facades\Cookie;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Http;
- class HomeController extends Controller
- {
- public function confirmSmsAuthToken(Request $request)
- {
- return view('app/confirm_sms_auth_token');
- }
- public function setPassword(Request $request)
- {
- return view('app/set_password');
- }
- public function setSecurityQuestions(Request $request)
- {
- return view('app/set_security_questions');
- }
- public function postConfirmSmsAuthToken(Request $request)
- {
- try {
- $url = config('stag.backendUrl') . '/session/confirmSmsAuthToken';
- $data = [
- 'cellNumber' => $request->input('cellNumber'),
- 'token' => $request->input('token'),
- ];
- $response = Http::asForm()
- ->withHeaders(['sessionKey' => $request->cookie('sessionKey')])
- ->post($url, $data)
- ->json();
- if (!isset($response['success']) || !$response['success']) {
- $message = 'API error';
- if (isset($response['error'])) {
- $message = $response['error'];
- if (isset($response['path'])) $message .= ': ' . $response['path'];
- } else if (isset($response['message'])) $message = $response['message'];
- return redirect('/confirm_sms_auth_token')
- ->withInput()
- ->with('message', $message);
- }
- return redirect('/');
- } catch (\Exception $e) {
- return redirect()->back()
- ->with('message', 'Unable to process your request at the moment. Please try again later.')
- ->withInput($request->input());
- }
- }
- public function resendSmsAuthToken(Request $request)
- {
- try {
- $url = config('stag.backendUrl') . '/session/resendSmsAuthToken';
- $data = [];
- $response = Http::asForm()
- ->withHeaders(['sessionKey' => $request->cookie('sessionKey')])
- ->post($url, $data)
- ->json();
- if (!isset($response['success']) || !$response['success']) {
- $message = 'API error';
- if (isset($response['error'])) {
- $message = $response['error'];
- if (isset($response['path'])) $message .= ': ' . $response['path'];
- } else if (isset($response['message'])) $message = $response['message'];
- return redirect('/confirm_sms_auth_token')
- ->withInput()
- ->with('message', $message);
- }
- return redirect()->back()->withInput()->with('message', "SMS Auth Token sent.");
- } catch (\Exception $e) {
- return redirect()->back()
- ->with('message', 'Unable to process your request at the moment. Please try again later.')
- ->withInput($request->input());
- }
- }
- public function postSetPassword(Request $request)
- {
- try {
- $url = config('stag.backendUrl') . '/pro/selfPutPassword';
- $data = [
- 'newPassword' => $request->input('newPassword'),
- 'newPasswordConfirmation' => $request->input('newPasswordConfirmation'),
- ];
- $response = Http::asForm()
- ->withHeaders(['sessionKey' => $request->cookie('sessionKey')])
- ->post($url, $data)
- ->json();
- if (!isset($response['success']) || !$response['success']) {
- $message = 'API error';
- if (isset($response['error'])) {
- $message = $response['error'];
- if (isset($response['path'])) $message .= ': ' . $response['path'];
- } else if (isset($response['message'])) $message = $response['message'];
- return redirect('/set_password')
- ->withInput()
- ->with('message', $message);
- }
- return redirect('/');
- } catch (\Exception $e) {
- return redirect()->back()
- ->with('message', 'Unable to process your request at the moment. Please try again later.')
- ->withInput($request->input());
- }
- }
- public function postSetSecurityQuestions(Request $request)
- {
- try {
- $url = env('BACKEND_URL', 'http://localhost:8080/api') . '/pro/selfPutSecurityQuestions';
- $data = [
- 'securityQuestion1' => $request->input('securityQuestion1'),
- 'securityAnswer1' => $request->input('securityAnswer1'),
- 'securityQuestion2' => $request->input('securityQuestion2'),
- 'securityAnswer2' => $request->input('securityAnswer2'),
- ];
- $response = Http::asForm()
- ->withHeaders(['sessionKey' => $request->cookie('sessionKey')])
- ->post($url, $data)
- ->json();
- if (!isset($response['success']) || !$response['success']) {
- $message = 'API error';
- if (isset($response['error'])) {
- $message = $response['error'];
- if (isset($response['path'])) $message .= ': ' . $response['path'];
- } else if (isset($response['message'])) $message = $response['message'];
- return redirect('/set_password')
- ->withInput()
- ->with('message', $message);
- }
- return redirect('/');
- } catch (\Exception $e) {
- return redirect()->back()
- ->with('message', 'Unable to process your request at the moment. Please try again later.')
- ->withInput($request->input());
- }
- }
- private function dashboard_MCP(Request $request){
- $keyNumbers = [];
- // Patients // SELECT * FROM client WHERE mcp_pro_id = :me.id;
- // New Patients Awaiting Visit // SELECT * FROM client WHERE mcp_pro_id = :me.id AND hasMcpDoneOnboardingVisit != 'YES';
- // 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;
- // 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;
- // Reports Pending Signature // SELECT * FROM incoming_report WHERE hcp_pro_id = :me.id AND isEntryError IS NOT TRUE AND hasHcpProSigned IS NOT TRUE;
- // Patients w/o Appointments // SELECT * FROM client WHERE mcp_pro_id = :me.id AND client.next_mcp_appointment_date < today();
- // Patients Overdue for Visit // SELECT * FROM client WHERE mcp_pro_id = :me.id AND client.next_expected_mcp_visit_date < today();
- // Cancelled Appts. Pending Review // SELECT * FROM appointment WHERE hcp_pro_id = :me.id AND status = 'REJECTED' AND wasAcknowledgedByAppointmentPro IS NOT TRUE;
- // Cancelled Bills Pending Review // SELECT * FROM bill WHERE bill_service_type = 'NOTE' AND is_cancelled IS TRUE AND isCancellationAcknowledged IS FALSE;
- // 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;
- // ERx & Orders Pending Signature // SELECT * FROM erx WHERE hcp_pro_id = :me.id AND pro_declared_status <> 'CANCELLED' AND hasHcpProSigned IS NOT TRUE;
- // 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;
- $performer = $this->performer();
- $pro = $performer->pro;
- $performerProID = $performer->pro->id;
- $keyNumbers = [];
- $queryClients = $this->performer()->pro->getAccessibleClientsQuery();
- $pendingNotesToSign = Note
- ::where(function ($query) use ($performerProID) {
- $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_cancelled', false)->where('is_core_note', false);
- })
- ->orWhere(function ($query) use ($performerProID) {
- $query->where('ally_pro_id', $performerProID)->where('is_signed_by_ally', false)->where('is_cancelled', false)->where('is_core_note', false);
- })
- ->count();
- $keyNumbers['pendingNotesToSign'] = $pendingNotesToSign;
- // notes pending mcp sign (applicable to dnas only)
- $pendingNotesToSignMCP = Note
- ::where(function ($query) use ($performerProID) {
- $query->where('ally_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_cancelled', false)->where('is_core_note', false);
- })
- ->count();
- $keyNumbers['$pendingNotesToSignMCP'] = $pendingNotesToSignMCP;
- $pendingNotesToSignAllySigned = Note::where(function ($query) use ($performerProID) {
- $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);;
- })->count();
- $keyNumbers['pendingNotesToSignAllySigned'] = $pendingNotesToSignAllySigned;
- $signedNotesWithoutBills = Note::where(function ($query) use ($performerProID) {
- $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', true)->where('is_cancelled', false);
- })->whereDoesntHave('bills')->count();
- $keyNumbers['signedNotesWithoutBills'] = $signedNotesWithoutBills;
- // open tickets
- $keyNumbers['numOpenTickets'] = Ticket::where('is_open', true)
- ->where(function ($q) use ($performerProID) {
- $q->where('assigned_pro_id', $performerProID)
- ->orWhere('manager_pro_id', $performerProID)
- ->orWhere('ordering_pro_id', $performerProID)
- ->orWhere('initiating_pro_id', $performerProID);
- })
- ->count();
- // unacknowledged cancelled bills for authed pro
- $keyNumbers['unacknowledgedCancelledBills'] = Bill::where('hcp_pro_id', $performerProID)
- ->where('is_cancelled', true)
- ->where('is_cancellation_acknowledged', false)
- ->count();
- // unacknowledged cancelled supply orders for authed pro
- $keyNumbers['unacknowledgedCancelledSupplyOrders'] = SupplyOrder::where('signed_by_pro_id', $performerProID)
- ->where('is_cancelled', true)
- ->where('is_cancellation_acknowledged', false)
- ->count();
- // unsigned supply orders created by authed pro
- $keyNumbers['unsignedSupplyOrders'] = SupplyOrder
- ::where('is_cancelled', false)
- ->where('is_signed_by_pro', false)
- ->whereRaw('created_by_session_id IN (SELECT id FROM app_session WHERE pro_id = ?)', [$performerProID])
- ->count();
- // patientsHavingBirthdayToday
- $queryClients = $this->performer()->pro->getAccessibleClientsQuery();
- $keyNumbers['patientsHavingBirthdayToday'] = $queryClients
- ->whereRaw('EXTRACT(DAY from dob) = ?', [date('d')])
- ->whereRaw('EXTRACT(MONTH from dob) = ?', [date('m')])
- ->count();
- $reimbursement = [];
- $reimbursement["currentBalance"] = $performer->pro->balance;
- $reimbursement["nextPaymentDate"] = '--';
- $lastPayment = ProTransaction::where('pro_id', $performerProID)->where('plus_or_minus', 'PLUS')->orderBy('created_at', 'DESC')->first();
- if ($lastPayment) {
- $reimbursement["lastPayment"] = $lastPayment->amount;
- $reimbursement["lastPaymentDate"] = $lastPayment->created_at;
- } else {
- $reimbursement["lastPayment"] = '--';
- $reimbursement["lastPaymentDate"] = '--';
- }
- //if today is < 15th, next payment is 15th, else nextPayment is
- $today = strtotime(date('Y-m-d'));
- $todayDate = date('j', $today);
- $todayMonth = date('m', $today);
- $todayYear = date('Y', $today);
- if ($todayDate < 15) {
- $nextPaymentDate = new DateTime();
- $nextPaymentDate->setDate($todayYear, $todayMonth, 15);
- $reimbursement['nextPaymentDate'] = $nextPaymentDate->format('m/d/Y');
- } else {
- $nextPaymentDate = new \DateTime();
- $lastDayOfMonth = date('t', $today);
- $nextPaymentDate->setDate($todayYear, $todayMonth, $lastDayOfMonth);
- $reimbursement['nextPaymentDate'] = $nextPaymentDate->format('m/d/Y');
- }
- //expectedPay
- $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;
- $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;
- $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;
- $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;
- $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;
- $totalExpectedAmount = $expectedForHcp + $expectedForCm + $expectedForRme + $expectedForRmm + $expectedForNa;
- $reimbursement['nextPaymentAmount'] = $totalExpectedAmount;
- $milliseconds = strtotime(date('Y-m-d')) . '000';
- // bills & claims
- $businessNumbers = [];
- // Notes with bills to resolve
- $businessNumbers['notesWithBillsToResolve'] = Note::where('is_cancelled', '!=', true)
- ->where('is_bill_closed', '!=', true)
- ->whereRaw('(SELECT count(id) FROM bill WHERE note_id = note.id AND is_cancelled = false AND is_verified = false) > 0')
- ->count();
- // Notes pending bill closure
- $businessNumbers['notesPendingBillingClosure'] = Note::where('is_cancelled', '!=', true)
- ->where('is_bill_closed', '!=', true)
- ->whereRaw('(SELECT count(id) FROM bill WHERE note_id = note.id AND (is_cancelled = true OR is_verified = true)) = 0')
- ->count();
- // incoming reports not signed
- $incomingReports = IncomingReport::where('hcp_pro_id', $performerProID)
- ->where('has_hcp_pro_signed', false)
- ->where('is_entry_error', false)
- ->orderBy('created_at', 'ASC')
- ->get();
- // erx, labs & imaging that are not closed
- $tickets = Ticket::where('ordering_pro_id', $performerProID)
- ->where('is_entry_error', false)
- ->where('is_open', true)
- ->orderBy('created_at', 'ASC')
- ->get();
- $supplyOrders = SupplyOrder::where('is_cleared_for_shipment', false)
- ->where('is_cancelled', false)
- ->whereRaw('created_by_session_id IN (SELECT id FROM app_session where pro_id = ?)', [$performer->pro->id])
- ->orderBy('created_at', 'ASC')
- ->get();
- $numERx = Ticket::where('ordering_pro_id', $performerProID)
- ->where('category', 'erx')
- ->where('is_entry_error', false)
- ->where('is_open', true)
- ->count();
- $numLabs = Ticket::where('ordering_pro_id', $performerProID)
- ->where('category', 'lab')
- ->where('is_entry_error', false)
- ->where('is_open', true)
- ->count();
- $numImaging = Ticket::where('ordering_pro_id', $performerProID)
- ->where('category', 'imaging')
- ->where('is_entry_error', false)
- ->where('is_open', true)
- ->count();
- $numSupplyOrders = SupplyOrder::where('is_cleared_for_shipment', false)
- ->where('is_cancelled', false)
- ->whereRaw('created_by_session_id IN (SELECT id FROM app_session where pro_id = ?)', [$performer->pro->id])
- ->count();
- $newMCPAssociations = ClientProChange
- ::where('new_pro_id', $performerProID)
- ->where('responsibility_type', 'MCP')
- ->whereNull('current_client_pro_change_decision_id')
- ->get();
- $newNAAssociations = ClientProChange
- ::where('new_pro_id', $performerProID)
- ->where('responsibility_type', 'DEFAULT_NA')
- ->whereNull('current_client_pro_change_decision_id')
- ->get();
- // unstamped client memos
- // for mcp
- $mcpClientMemos = DB::select(
- DB::raw("
- SELECT c.uid as client_uid, c.name_first, c.name_last,
- cm.uid, cm.content, cm.created_at
- FROM client c join client_memo cm on c.id = cm.client_id
- WHERE
- c.mcp_pro_id = {$performerProID} AND
- cm.mcp_stamp_id IS NULL
- AND (is_admin_only IS FALSE OR is_admin_only IS NULL)
- ORDER BY cm.created_at DESC
- OFFSET 0 LIMIT 10
- ")
- );
- $mcpClientMemosCount = DB::select(
- DB::raw("
- SELECT count(c.uid)
- FROM client c join client_memo cm on c.id = cm.client_id
- WHERE
- c.mcp_pro_id = {$performerProID} AND
- cm.mcp_stamp_id IS NULL
- AND (is_admin_only IS FALSE OR is_admin_only IS NULL)
- ")
- );
- if($mcpClientMemosCount && count($mcpClientMemosCount)) {
- $mcpClientMemosCount = $mcpClientMemosCount[0]->count;
- }
- // for na
- $naClientMemos = DB::select(
- DB::raw("
- SELECT c.uid as client_uid, c.name_first, c.name_last,
- cm.uid, cm.content, cm.created_at
- FROM client c join client_memo cm on c.id = cm.client_id
- WHERE
- c.default_na_pro_id = {$performerProID} AND
- cm.default_na_stamp_id IS NULL
- ORDER BY cm.created_at DESC
- ")
- );
- $keyNumbers['rmBillsToSign'] = Bill
- ::where('is_cancelled', false)
- ->where('cm_or_rm', 'RM')
- ->where(function ($q) use ($performerProID) {
- $q
- ->where(function ($q2) use ($performerProID) {
- $q2->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false);
- })
- ->orWhere(function ($q2) use ($performerProID) {
- $q2->where('rme_pro_id', $performerProID)->where('is_signed_by_rme', false);
- })
- ->orWhere(function ($q2) use ($performerProID) {
- $q2->where('rmm_pro_id', $performerProID)->where('is_signed_by_rmm', false);
- })
- ->orWhere(function ($q2) use ($performerProID) {
- $q2->where('generic_pro_id', $performerProID)->where('is_signed_by_generic_pro', false);
- });
- })
- ->count();
- $count = DB::select(
- DB::raw(
- "
- SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
- WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
- OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
- AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
- AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
- AND (care_month.number_of_days_with_remote_measurements < 16 OR care_month.number_of_days_with_remote_measurements IS NULL)
- "
- )
- );
- $keyNumbers['rmPatientsWithLT16MD'] = $count[0]->cnt;
- $count = DB::select(
- DB::raw(
- "
- SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
- WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
- OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
- AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
- AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
- AND (care_month.number_of_days_with_remote_measurements >= 16 AND care_month.number_of_days_with_remote_measurements IS NOT NULL)
- "
- )
- );
- $keyNumbers['rmPatientsWithGTE16MD'] = $count[0]->cnt;
- $count = DB::select(
- DB::raw(
- "
- SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
- WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
- OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
- AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
- AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
- 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)
- "
- )
- );
- $keyNumbers['rmPatientsWithWhomCommDone'] = $count[0]->cnt;
- $count = DB::select(
- DB::raw(
- "
- SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
- WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
- OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
- AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
- AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
- 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)
- "
- )
- );
- $keyNumbers['rmPatientsWithWhomCommNotDone'] = $count[0]->cnt;
- // num measurements that need stamping
- $keyNumbers['measurementsToBeStamped'] = $this->performer()->pro->getUnstampedMeasurementsFromCurrentMonth(true, null, null);
- if($performer->pro->pro_type === 'ADMIN') {
- // patients without coverage information
- $keyNumbers['patientsWithoutCoverageInformation'] = DB::select(DB::raw("
- SELECT count(DISTINCT (cl.id)) as cnt
- FROM client cl
- WHERE cl.shadow_pro_id IS NULL AND cl.latest_client_primary_coverage_id IS NULL -- no coverage record"
- ))[0]->cnt;
- // patients pending coverage verification
- $keyNumbers['patientsPendingCoverageVerification'] = DB::select(DB::raw("
- SELECT count(DISTINCT (cl.id)) as cnt
- FROM client cl
- LEFT JOIN client_primary_coverage cpc ON cl.latest_client_primary_coverage_id = cpc.id
- WHERE cl.shadow_pro_id IS NULL
- AND (cl.latest_client_primary_coverage_id IS NOT NULL -- coverage exists, but status is null or unknown
- AND (
- (cpc.plan_type = 'MEDICARE' AND (cpc.is_partbprimary = 'UNKNOWN' OR cpc.is_partbprimary IS NULL))
- OR
- (cpc.plan_type != 'MEDICARE' AND
- (cpc.manual_determination_category = 'UNKNOWN' OR cpc.manual_determination_category IS NULL))
- ))"
- ))[0]->cnt;
- }
- $incomingSmsMessagesPendingReply = DB::select("
- 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
- WHERE cs.is_reply_needed = 'YES' AND c.mcp_pro_id = :mcp_pro_id AND incoming_or_outgoing = 'INCOMING'
- AND (cs.created_at > c.last_sms_sent_to_client_at OR c.last_sms_sent_to_client_at IS NULL)
- ORDER BY created_at DESC
- ", ['mcp_pro_id' => $performer->pro->id]);
- $careMonthsWithMeasurementsPendingStamping = CareMonth::select('id')
- ->where('mcp_pro_id', $this->performer->pro->id)
- ->where('rm_num_measurements_not_stamped_by_mcp', '>', 0)
- ->whereNotNull('rm_num_measurements_not_stamped_by_mcp')
- ->orderBy('created_at', 'DESC')
- ->get()
- ->map(function($_x) {
- return $_x->id;
- })
- ->toArray();
- $measurementsPendingStamping = Measurement::whereIn('care_month_id', $careMonthsWithMeasurementsPendingStamping)
- ->orderBy('created_at', 'DESC')
- ->whereNotNull('ts')
- ->whereNotIn('label', ['SBP', 'DBP'])
- ->where('is_cellular_zero', '<>', true)
- ->where('is_removed', false)
- ->where('has_been_stamped_by_mcp', false)
- ->whereNotNull('client_bdt_measurement_id')
- ->paginate(15);
- return view('app/dashboard-mcp', compact('keyNumbers', 'reimbursement', 'milliseconds',
- 'businessNumbers',
- 'incomingReports', 'tickets', 'supplyOrders',
- 'numERx', 'numLabs', 'numImaging', 'numSupplyOrders',
- 'newMCPAssociations', 'newNAAssociations',
- 'measurementsPendingStamping', 'careMonthsWithMeasurementsPendingStamping',
- 'mcpClientMemos', 'mcpClientMemosCount', 'naClientMemos', 'incomingSmsMessagesPendingReply'));
- }
- private function dashboard_DNA(Request $request){
- $performer = $this->performer();
- $pro = $performer->pro;
- $performerProID = $performer->pro->id;
- $milliseconds = strtotime(date('Y-m-d')) . '000'; //required by the calendar
- return view('app/dashboard-dna', compact( 'milliseconds'));
- }
- private function dashboard_ADMIN(Request $request){
- $keyNumbers = [];
- // Patients // SELECT * FROM client WHERE mcp_pro_id = :me.id;
- // New Patients Awaiting Visit // SELECT * FROM client WHERE mcp_pro_id = :me.id AND hasMcpDoneOnboardingVisit != 'YES';
- // 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;
- // 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;
- // Reports Pending Signature // SELECT * FROM incoming_report WHERE hcp_pro_id = :me.id AND isEntryError IS NOT TRUE AND hasHcpProSigned IS NOT TRUE;
- // Patients w/o Appointments // SELECT * FROM client WHERE mcp_pro_id = :me.id AND client.next_mcp_appointment_date < today();
- // Patients Overdue for Visit // SELECT * FROM client WHERE mcp_pro_id = :me.id AND client.next_expected_mcp_visit_date < today();
- // Cancelled Appts. Pending Review // SELECT * FROM appointment WHERE hcp_pro_id = :me.id AND status = 'REJECTED' AND wasAcknowledgedByAppointmentPro IS NOT TRUE;
- // Cancelled Bills Pending Review // SELECT * FROM bill WHERE bill_service_type = 'NOTE' AND is_cancelled IS TRUE AND isCancellationAcknowledged IS FALSE;
- // 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;
- // ERx & Orders Pending Signature // SELECT * FROM erx WHERE hcp_pro_id = :me.id AND pro_declared_status <> 'CANCELLED' AND hasHcpProSigned IS NOT TRUE;
- // 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;
- $performer = $this->performer();
- $pro = $performer->pro;
- $performerProID = $performer->pro->id;
- $keyNumbers = [];
- $queryClients = $this->performer()->pro->getAccessibleClientsQuery();
- $pendingNotesToSign = Note
- ::where(function ($query) use ($performerProID) {
- $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_cancelled', false)->where('is_core_note', false);
- })
- ->orWhere(function ($query) use ($performerProID) {
- $query->where('ally_pro_id', $performerProID)->where('is_signed_by_ally', false)->where('is_cancelled', false)->where('is_core_note', false);
- })
- ->count();
- $keyNumbers['pendingNotesToSign'] = $pendingNotesToSign;
- // notes pending mcp sign (applicable to dnas only)
- $pendingNotesToSignMCP = Note
- ::where(function ($query) use ($performerProID) {
- $query->where('ally_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_cancelled', false)->where('is_core_note', false);
- })
- ->count();
- $keyNumbers['$pendingNotesToSignMCP'] = $pendingNotesToSignMCP;
- $pendingNotesToSignAllySigned = Note::where(function ($query) use ($performerProID) {
- $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);;
- })->count();
- $keyNumbers['pendingNotesToSignAllySigned'] = $pendingNotesToSignAllySigned;
- $signedNotesWithoutBills = Note::where(function ($query) use ($performerProID) {
- $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', true)->where('is_cancelled', false);
- })->whereDoesntHave('bills')->count();
- $keyNumbers['signedNotesWithoutBills'] = $signedNotesWithoutBills;
- // open tickets
- $keyNumbers['numOpenTickets'] = Ticket::where('is_open', true)
- ->where(function ($q) use ($performerProID) {
- $q->where('assigned_pro_id', $performerProID)
- ->orWhere('manager_pro_id', $performerProID)
- ->orWhere('ordering_pro_id', $performerProID)
- ->orWhere('initiating_pro_id', $performerProID);
- })
- ->count();
- // unacknowledged cancelled bills for authed pro
- $keyNumbers['unacknowledgedCancelledBills'] = Bill::where('hcp_pro_id', $performerProID)
- ->where('is_cancelled', true)
- ->where('is_cancellation_acknowledged', false)
- ->count();
- // unacknowledged cancelled supply orders for authed pro
- $keyNumbers['unacknowledgedCancelledSupplyOrders'] = SupplyOrder::where('signed_by_pro_id', $performerProID)
- ->where('is_cancelled', true)
- ->where('is_cancellation_acknowledged', false)
- ->count();
- // unsigned supply orders created by authed pro
- $keyNumbers['unsignedSupplyOrders'] = SupplyOrder
- ::where('is_cancelled', false)
- ->where('is_signed_by_pro', false)
- ->whereRaw('created_by_session_id IN (SELECT id FROM app_session WHERE pro_id = ?)', [$performerProID])
- ->count();
- // patientsHavingBirthdayToday
- $queryClients = $this->performer()->pro->getAccessibleClientsQuery();
- $keyNumbers['patientsHavingBirthdayToday'] = $queryClients
- ->whereRaw('EXTRACT(DAY from dob) = ?', [date('d')])
- ->whereRaw('EXTRACT(MONTH from dob) = ?', [date('m')])
- ->count();
- $reimbursement = [];
- $reimbursement["currentBalance"] = $performer->pro->balance;
- $reimbursement["nextPaymentDate"] = '--';
- $lastPayment = ProTransaction::where('pro_id', $performerProID)->where('plus_or_minus', 'PLUS')->orderBy('created_at', 'DESC')->first();
- if ($lastPayment) {
- $reimbursement["lastPayment"] = $lastPayment->amount;
- $reimbursement["lastPaymentDate"] = $lastPayment->created_at;
- } else {
- $reimbursement["lastPayment"] = '--';
- $reimbursement["lastPaymentDate"] = '--';
- }
- //if today is < 15th, next payment is 15th, else nextPayment is
- $today = strtotime(date('Y-m-d'));
- $todayDate = date('j', $today);
- $todayMonth = date('m', $today);
- $todayYear = date('Y', $today);
- if ($todayDate < 15) {
- $nextPaymentDate = new DateTime();
- $nextPaymentDate->setDate($todayYear, $todayMonth, 15);
- $reimbursement['nextPaymentDate'] = $nextPaymentDate->format('m/d/Y');
- } else {
- $nextPaymentDate = new \DateTime();
- $lastDayOfMonth = date('t', $today);
- $nextPaymentDate->setDate($todayYear, $todayMonth, $lastDayOfMonth);
- $reimbursement['nextPaymentDate'] = $nextPaymentDate->format('m/d/Y');
- }
- //expectedPay
- $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;
- $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;
- $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;
- $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;
- $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;
- $totalExpectedAmount = $expectedForHcp + $expectedForCm + $expectedForRme + $expectedForRmm + $expectedForNa;
- $reimbursement['nextPaymentAmount'] = $totalExpectedAmount;
- $milliseconds = strtotime(date('Y-m-d')) . '000';
- // bills & claims
- $businessNumbers = [];
- // Notes with bills to resolve
- $businessNumbers['notesWithBillsToResolve'] = Note::where('is_cancelled', '!=', true)
- ->where('is_bill_closed', '!=', true)
- ->whereRaw('(SELECT count(id) FROM bill WHERE note_id = note.id AND is_cancelled = false AND is_verified = false) > 0')
- ->count();
- // Notes pending bill closure
- $businessNumbers['notesPendingBillingClosure'] = Note::where('is_cancelled', '!=', true)
- ->where('is_bill_closed', '!=', true)
- ->whereRaw('(SELECT count(id) FROM bill WHERE note_id = note.id AND (is_cancelled = true OR is_verified = true)) = 0')
- ->count();
- // incoming reports not signed
- $incomingReports = IncomingReport::where('hcp_pro_id', $performerProID)
- ->where('has_hcp_pro_signed', false)
- ->where('is_entry_error', false)
- ->orderBy('created_at', 'ASC')
- ->get();
- // erx, labs & imaging that are not closed
- $tickets = Ticket::where('ordering_pro_id', $performerProID)
- ->where('is_entry_error', false)
- ->where('is_open', true)
- ->orderBy('created_at', 'ASC')
- ->get();
- $supplyOrders = SupplyOrder::where('is_cleared_for_shipment', false)
- ->where('is_cancelled', false)
- ->whereRaw('created_by_session_id IN (SELECT id FROM app_session where pro_id = ?)', [$performer->pro->id])
- ->orderBy('created_at', 'ASC')
- ->get();
- $numERx = Ticket::where('ordering_pro_id', $performerProID)
- ->where('category', 'erx')
- ->where('is_entry_error', false)
- ->where('is_open', true)
- ->count();
- $numLabs = Ticket::where('ordering_pro_id', $performerProID)
- ->where('category', 'lab')
- ->where('is_entry_error', false)
- ->where('is_open', true)
- ->count();
- $numImaging = Ticket::where('ordering_pro_id', $performerProID)
- ->where('category', 'imaging')
- ->where('is_entry_error', false)
- ->where('is_open', true)
- ->count();
- $numSupplyOrders = SupplyOrder::where('is_cleared_for_shipment', false)
- ->where('is_cancelled', false)
- ->whereRaw('created_by_session_id IN (SELECT id FROM app_session where pro_id = ?)', [$performer->pro->id])
- ->count();
- $newMCPAssociations = ClientProChange
- ::where('new_pro_id', $performerProID)
- ->where('responsibility_type', 'MCP')
- ->whereNull('current_client_pro_change_decision_id')
- ->get();
- $newNAAssociations = ClientProChange
- ::where('new_pro_id', $performerProID)
- ->where('responsibility_type', 'DEFAULT_NA')
- ->whereNull('current_client_pro_change_decision_id')
- ->get();
- $proApptUpdates = AppointmentConfirmationDecision
- ::select('appointment_confirmation_decision.uid', 'client.name_first', 'client.name_last', 'appointment.start_time')
- ->rightJoin('appointment', 'appointment.id', '=', 'appointment_confirmation_decision.appointment_id')
- ->rightJoin('client', 'client.id', '=', 'appointment.client_id')
- ->where('appointment_confirmation_decision.was_acknowledged_by_appointment_pro', false)
- ->where('appointment.status', '!=', 'CREATED')
- ->where('appointment.status', '!=', 'COMPLETED')
- ->where('appointment.status', '!=', 'ABANDONED')
- ->where('appointment.pro_id', $performerProID)
- ->where('client.mcp_pro_id', $performerProID)
- ->orderBy('appointment.start_time', 'DESC')
- ->get();
- $naApptUpdates = AppointmentConfirmationDecision
- ::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')
- ->rightJoin('appointment', 'appointment.id', '=', 'appointment_confirmation_decision.appointment_id')
- ->rightJoin('client', 'client.id', '=', 'appointment.client_id')
- ->rightJoin('pro', 'pro.id', '=', 'appointment.pro_id')
- ->where('appointment_confirmation_decision.was_acknowledged_by_client_default_na', false)
- ->where('appointment.status', '!=', 'CREATED')
- ->where('appointment.status', '!=', 'COMPLETED')
- ->where('appointment.status', '!=', 'ABANDONED')
- ->where('client.default_na_pro_id', $performerProID)
- ->orderBy('appointment.start_time', 'DESC')
- ->get();
- // $naApptUpdates = AppointmentConfirmationDecision
- // ::join('appointment', 'appointment.id', '=', 'appointment_confirmation_decision.appointment_id')
- // ->join('client', 'client.id', '=', 'appointment.client_id')
- // ->where('client.default_na_pro_id', $performerProID)
- // ->where('appointment_confirmation_decision.was_acknowledged_by_client_default_na', false)
- // ->orderBy('appointment.start_time DESC')
- // ->get();
- // unstamped client memos
- // for mcp
- $mcpClientMemos = DB::select(
- DB::raw("
- SELECT c.uid as client_uid, c.name_first, c.name_last,
- cm.uid, cm.content, cm.created_at
- FROM client c join client_memo cm on c.id = cm.client_id
- WHERE
- c.mcp_pro_id = {$performerProID} AND
- cm.mcp_stamp_id IS NULL
- ORDER BY cm.created_at DESC
- ")
- );
- // for na
- $naClientMemos = DB::select(
- DB::raw("
- SELECT c.uid as client_uid, c.name_first, c.name_last,
- cm.uid, cm.content, cm.created_at
- FROM client c join client_memo cm on c.id = cm.client_id
- WHERE
- c.default_na_pro_id = {$performerProID} AND
- cm.default_na_stamp_id IS NULL
- ORDER BY cm.created_at DESC
- ")
- );
- $keyNumbers['rmBillsToSign'] = Bill
- ::where('is_cancelled', false)
- ->where('cm_or_rm', 'RM')
- ->where(function ($q) use ($performerProID) {
- $q
- ->where(function ($q2) use ($performerProID) {
- $q2->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false);
- })
- ->orWhere(function ($q2) use ($performerProID) {
- $q2->where('rme_pro_id', $performerProID)->where('is_signed_by_rme', false);
- })
- ->orWhere(function ($q2) use ($performerProID) {
- $q2->where('rmm_pro_id', $performerProID)->where('is_signed_by_rmm', false);
- })
- ->orWhere(function ($q2) use ($performerProID) {
- $q2->where('generic_pro_id', $performerProID)->where('is_signed_by_generic_pro', false);
- });
- })
- ->count();
- $count = DB::select(
- DB::raw(
- "
- SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
- WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
- OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
- AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
- AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
- AND (care_month.number_of_days_with_remote_measurements < 16 OR care_month.number_of_days_with_remote_measurements IS NULL)
- "
- )
- );
- $keyNumbers['rmPatientsWithLT16MD'] = $count[0]->cnt;
- $count = DB::select(
- DB::raw(
- "
- SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
- WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
- OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
- AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
- AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
- AND (care_month.number_of_days_with_remote_measurements >= 16 AND care_month.number_of_days_with_remote_measurements IS NOT NULL)
- "
- )
- );
- $keyNumbers['rmPatientsWithGTE16MD'] = $count[0]->cnt;
- $count = DB::select(
- DB::raw(
- "
- SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
- WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
- OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
- AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
- AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
- 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)
- "
- )
- );
- $keyNumbers['rmPatientsWithWhomCommDone'] = $count[0]->cnt;
- $count = DB::select(
- DB::raw(
- "
- SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
- WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
- OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
- AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
- AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
- 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)
- "
- )
- );
- $keyNumbers['rmPatientsWithWhomCommNotDone'] = $count[0]->cnt;
- // num measurements that need stamping
- $keyNumbers['measurementsToBeStamped'] = $this->performer()->pro->getUnstampedMeasurementsFromCurrentMonth(true, null, null);
- if($performer->pro->pro_type === 'ADMIN') {
- // patients without coverage information
- $keyNumbers['patientsWithoutCoverageInformation'] = DB::select(DB::raw("
- SELECT count(DISTINCT (cl.id)) as cnt
- FROM client cl
- WHERE cl.shadow_pro_id IS NULL AND cl.latest_client_primary_coverage_id IS NULL -- no coverage record"
- ))[0]->cnt;
- // patients pending coverage verification
- $keyNumbers['patientsPendingCoverageVerification'] = DB::select(DB::raw("
- SELECT count(DISTINCT (cl.id)) as cnt
- FROM client cl
- LEFT JOIN client_primary_coverage cpc ON cl.latest_client_primary_coverage_id = cpc.id
- WHERE cl.shadow_pro_id IS NULL
- AND (cl.latest_client_primary_coverage_id IS NOT NULL -- coverage exists, but status is null or unknown
- AND (
- (cpc.plan_type = 'MEDICARE' AND (cpc.is_partbprimary = 'UNKNOWN' OR cpc.is_partbprimary IS NULL))
- OR
- (cpc.plan_type != 'MEDICARE' AND
- (cpc.manual_determination_category = 'UNKNOWN' OR cpc.manual_determination_category IS NULL))
- ))"
- ))[0]->cnt;
- }
- return view('app/dashboard-admin', compact('keyNumbers', 'reimbursement', 'milliseconds',
- 'businessNumbers',
- 'incomingReports', 'tickets', 'supplyOrders',
- 'numERx', 'numLabs', 'numImaging', 'numSupplyOrders',
- 'newMCPAssociations', 'newNAAssociations',
- 'mcpClientMemos', 'naClientMemos',
- 'proApptUpdates', 'naApptUpdates'));
- }
- public function dashboard(Request $request)
- {
- $performer = $this->performer();
- $pro = $performer->pro;
- if($pro->is_enrolled_as_mcp){
- return $this->dashboard_MCP($request);
- }elseif($pro->pro_type === 'ADMIN'){
- return $this->dashboard_ADMIN($request);
- }else{
- return $this->dashboard_DNA($request);
- }
- }
- public function dashboardMeasurementsTab(Request $request, $page = 1) {
- $performer = $this->performer();
- $myClientIDs = [];
- if ($performer->pro->pro_type != 'ADMIN') {
- $myClientIDs = $this->getMyClientIds();
- $myClientIDs = implode(", ", $myClientIDs);
- }
- $ifNotAdmin = " AND (
- client.mcp_pro_id = {$performer->pro->id}
- OR client.rmm_pro_id = {$performer->pro->id}
- OR client.rme_pro_id = {$performer->pro->id}
- OR client.physician_pro_id = {$performer->pro->id}
- OR client.id in (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = {$performer->pro->id})
- OR client.id in (SELECT client_id FROM appointment WHERE status NOT IN ('CANCELLED') AND pro_id = {$performer->pro->id})
- )";
- $numMeasurements = DB::select(
- DB::raw(
- "
- SELECT count(measurement.id) as cnt
- FROM measurement
- join client on measurement.client_id = client.id
- WHERE measurement.label NOT IN ('SBP', 'DBP')
- AND (measurement.is_cellular_zero = FALSE or measurement.is_cellular_zero IS NULL)
- AND measurement.is_removed IS FALSE
- AND measurement.has_been_stamped_by_mcp IS FALSE
- AND measurement.ts IS NOT NULL
- AND measurement.client_bdt_measurement_id IS NOT NULL
- AND (measurement.status IS NULL OR (measurement.status <> 'ACK' AND measurement.status <> 'INVALID_ACK'))
- AND EXTRACT(MONTH from measurement.created_at) = EXTRACT(MONTH from NOW())
- AND EXTRACT(YEAR from measurement.created_at) = EXTRACT(YEAR from NOW())
- " .
- (
- $performer->pro->pro_type != 'ADMIN' ? $ifNotAdmin : ''
- )
- )
- );
- $numMeasurements = $numMeasurements[0]->cnt;
- $measurements = DB::select(
- DB::raw(
- "
- SELECT measurement.uid as uid,
- care_month.uid as care_month_uid,
- care_month.start_date as care_month_start_date,
- measurement.label,
- measurement.value,
- measurement.sbp_mm_hg,
- measurement.dbp_mm_hg,
- measurement.numeric_value,
- measurement.value_pulse,
- measurement.value_irregular,
- measurement.ts,
- client.id as client_id,
- client.mcp_pro_id,
- client.default_na_pro_id,
- client.rmm_pro_id,
- client.rme_pro_id,
- client.uid as client_uid,
- client.name_last,
- client.name_first,
- care_month.rm_total_time_in_seconds
- FROM measurement
- join client on measurement.client_id = client.id
- join care_month on client.id = care_month.client_id
- WHERE measurement.label NOT IN ('SBP', 'DBP')
- AND (measurement.is_cellular_zero = FALSE or measurement.is_cellular_zero IS NULL)
- AND measurement.is_removed IS FALSE
- AND measurement.has_been_stamped_by_mcp IS FALSE
- AND measurement.ts IS NOT NULL
- AND measurement.client_bdt_measurement_id IS NOT NULL
- AND (measurement.status IS NULL OR (measurement.status <> 'ACK' AND measurement.status <> 'INVALID_ACK'))
- AND EXTRACT(MONTH from measurement.created_at) = EXTRACT(MONTH from NOW())
- AND EXTRACT(YEAR from measurement.created_at) = EXTRACT(YEAR from NOW())
- AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from NOW())
- AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from NOW())
- " .
- (
- $performer->pro->pro_type != 'ADMIN' ? $ifNotAdmin : ''
- )
- ) .
- " ORDER BY measurement.ts DESC LIMIT 20 OFFSET " . (($page - 1) * 20)
- );
- return view('app.dashboard.measurements', compact('numMeasurements', 'measurements', 'page'));
- }
- public function dashboardAppointmentDates(Request $request, $from, $to) {
- $performer = $this->performer();
- $performerProID = $performer->pro->id;
- $isAdmin = ($performer->pro->pro_type === 'ADMIN');
- $results = DB::table('appointment')->select('raw_date')->distinct()->where("start_time", '>=', $from)->where("start_time", '<=', $to.' 23:59:00+00');
- $results = $results->leftJoin('client AS c', 'c.id', '=', 'appointment.id');
- if(!$isAdmin) {
- $results = $results->where(function($query) use ($performerProID){
- return $query->where('appointment.pro_id', $performerProID)
- ->orWhere('c.default_na_pro_id', $performerProID);
- });
- }
- $results = $results->get();
- $dates = [];
- foreach ($results as $result) {
- // $dates[] = strtotime($result->raw_date) . '000';
- $dates[] = $result->raw_date;
- }
- // foreach ($results as $result) {
- // $results->dateYMD = date('Y-m-d', strtotime($result->raw_date));
- // }
- return json_encode($dates);
- }
- public function dashboardAppointments(Request $request, $from, $to) {
- $performer = $this->performer();
- $performerProID = $performer->pro->id;
- $isAdmin = ($performer->pro->pro_type === 'ADMIN');
- // $appointments = Appointment::where("start_time", '>=', $from)->where("start_time", '<=', $to.' 23:59:00+00');
- $appointments = Appointment::where("raw_date", '=', $from);
- if(!$isAdmin) {
- $appointments = $appointments->where(function($q) use ($performerProID) {
- return $q->where("pro_id", $performerProID)
- ->orWhereHas('client', function($clientQuery) use ($performerProID){
- return $clientQuery->where('default_na_pro_id', $performerProID);
- });
- });
- }
- $appointments = $appointments
- // ->whereRaw('status NOT IN (\'CANCELLED\', \'COMPLETED\')')
- ->orderBy('start_time', 'asc')
- ->get();
- foreach ($appointments as $appointment) {
- $date = explode(" ", $appointment->start_time)[0];
- $appointment->milliseconds = strtotime($date) . '000';
- $appointment->newStatus = $appointment->status;
- $appointment->dateYMD = date('Y-m-d', strtotime($appointment->raw_date));
- $appointment->clientName = $appointment->client->displayName();
- $appointment->clientInitials = substr($appointment->client->name_first, 0, 1) . substr($appointment->client->name_last, 0, 1);
- $appointment->isClientShadowOfPro = $appointment->client->shadow_pro_id ? true : false;
- $appointment->proInitials = substr($appointment->pro->name_first, 0, 1) . substr($appointment->pro->name_last, 0, 1);
- $appointment->friendlyStartTime = friendly_time($appointment->raw_start_time);
- $appointment->friendlyEndTime = friendly_time($appointment->raw_end_time);
- $appointment->clientSummary = friendly_date_time($appointment->client->dob, false) . ' (' .
- $appointment->client->age_in_years . ' y.o' .
- ($appointment->client->sex ? ' ' . $appointment->client->sex : '') .
- ')';
- $appointment->clientAge = $appointment->client->age_in_years;
- $appointment->clientSex = $appointment->client->sex;
- $appointment->started = false;
- $appointment->inHowManyHours = date_diff(date_create('now'), date_create($appointment->start_time), false)
- ->format('%R%h h, %i m');
- if ($appointment->inHowManyHours[0] === '-') {
- $appointment->inHowManyHours = substr($appointment->inHowManyHours, 1) . ' ago';
- $appointment->started = true;
- } else {
- $appointment->inHowManyHours = 'Appt. in ' . substr($appointment->inHowManyHours, 1);
- }
- $appointment->clientUid = $appointment->client->uid;
- $appointment->proUid = $appointment->pro->uid;
- $appointment->proName = $appointment->pro->displayName();
- // insurance information
- $appointment->coverage = $appointment->client->getPrimaryCoverageStatus();
- unset($appointment->client);
- unset($appointment->pro);
- unset($appointment->detail_json);
- }
- return json_encode($appointments);
- }
- public function dashboardAppointmentsDisplay(Request $request, $from, $to) {
- $performer = $this->performer();
- $performerProID = $performer->pro->id;
- $isAdmin = ($performer->pro->pro_type === 'ADMIN');
- // $appointments = Appointment::where("start_time", '>=', $from)->where("start_time", '<=', $to.' 23:59:00+00');
- $appointments = Appointment::where("raw_date", '=', $from);
- if(!$isAdmin) {
- $appointments = $appointments->where(function($q) use ($performerProID) {
- return $q->where("pro_id", $performerProID)
- ->orWhereHas('client', function($clientQuery) use ($performerProID){
- return $clientQuery->where('default_na_pro_id', $performerProID);
- });
- });
- }
- $appointments = $appointments
- ->orderBy('start_time', 'asc')
- ->orderBy('end_time', 'asc')
- ->get();
- foreach ($appointments as $appointment) {
- $date = explode(" ", $appointment->start_time)[0];
- $appointment->milliseconds = strtotime($date) . '000';
- $appointment->newStatus = $appointment->status;
- $appointment->dateYMD = date('Y-m-d', strtotime($appointment->raw_date));
- $appointment->clientName = $appointment->client->displayName();
- $appointment->clientInitials = substr($appointment->client->name_first, 0, 1) . substr($appointment->client->name_last, 0, 1);
- $appointment->isClientShadowOfPro = $appointment->client->shadow_pro_id ? true : false;
- $appointment->proInitials = substr($appointment->pro->name_first, 0, 1) . substr($appointment->pro->name_last, 0, 1);
- $appointment->friendlyStartTime = friendly_time($appointment->raw_start_time);
- $appointment->friendlyEndTime = friendly_time($appointment->raw_end_time);
- $appointment->clientSummary = friendly_date_time($appointment->client->dob, false) . ' (' .
- $appointment->client->age_in_years . ' y.o' .
- ($appointment->client->sex ? ' ' . $appointment->client->sex : '') .
- ')';
- $appointment->clientAge = $appointment->client->age_in_years;
- $appointment->clientSex = $appointment->client->sex;
- $appointment->started = false;
- $appointment->inHowManyHours = date_diff(date_create('now'), date_create($appointment->start_time), false)
- ->format('%R%h h, %i m');
- if ($appointment->inHowManyHours[0] === '-') {
- $appointment->inHowManyHours = substr($appointment->inHowManyHours, 1) . ' ago';
- $appointment->started = true;
- } else {
- $appointment->inHowManyHours = 'Appt. in ' . substr($appointment->inHowManyHours, 1);
- }
- $appointment->clientUid = $appointment->client->uid;
- $appointment->proUid = $appointment->pro->uid;
- $appointment->proName = $appointment->pro->displayName();
- // insurance information
- $appointment->coverage = $appointment->client->getPrimaryCoverageStatus();
- // bg color
- $appointment->bgColor = 'bg-white';
- if($appointment->status === 'COMPLETED') {
- $appointment->bgColor = 'event-bg-green';
- }
- else if($appointment->status === 'CANCELLED') {
- $appointment->bgColor = 'event-bg-gray';
- }
- unset($appointment->client);
- unset($appointment->pro);
- unset($appointment->detail_json);
- }
- return view('app.mcp.dashboard.appointments-list', compact('appointments', 'from', 'to'));
- }
- public function dashboardMeasurements(Request $request, $filter) {
- $measurements = $this->performer()->pro->getMeasurements($filter === 'NEED_ACK');
- return json_encode($measurements);
- }
- public function patients(Request $request, $filter = '')
- {
- $performer = $this->performer();
- $query = $performer->pro->getAccessibleClientsQuery();
- $q = trim($request->input('q'));
- if(!empty($q)) {
- $query = $query->where(function ($query) use ($q) {
- $query->where('name_first', 'ILIKE', "%$q%")
- ->orWhere('name_last', 'ILIKE', "%$q%")
- ->orWhere('email_address', 'ILIKE', "%$q%")
- ->orWhere('tags', 'ILIKE', "%$q%");
- });
- }
- switch ($filter) {
- case 'not-yet-seen':
- $query = $query
- ->where(function ($query) use ($performer) {
- $query
- ->where(function ($query) use ($performer) { // own patient and primary OB visit pending
- $query->where('mcp_pro_id', $performer->pro->id)
- ->where('has_mcp_done_onboarding_visit', '<>', 'YES');
- })
- ->orWhere(function ($query) use ($performer) { // mcp of any client program and program OB pending
- $query->select(DB::raw('COUNT(id)'))
- ->from('client_program')
- ->whereColumn('client_id', 'client.id')
- ->where('mcp_pro_id', $performer->pro->id)
- ->where('has_mcp_done_onboarding_visit', '<>', 'YES');
- }, '>=', 1);
- });
- break;
- case 'having-birthday-today':
- $query = $query
- ->whereRaw('EXTRACT(DAY from dob) = ?', [date('d')])
- ->whereRaw('EXTRACT(MONTH from dob) = ?', [date('m')]);
- break;
- // more cases can be added as needed
- default:
- break;
- }
- $patients = $query->orderBy('id', 'desc')->paginate(50);
- // patient acquisition chart (admin only)
- $patientAcquisitionData = null;
- if($performer->pro->pro_type === 'ADMIN') {
- $startDate = date_sub(date_create(), date_interval_create_from_date_string("1 month"));
- $startDate = date_format($startDate, "Y-m-d");
- $patientAcquisitionData = DB::select(DB::raw(
- "SELECT count(id) as count, DATE(created_at at time zone 'utc' at time zone 'est') as date " .
- "FROM client " .
- "WHERE shadow_pro_id IS NULL " .
- "GROUP BY DATE(created_at at time zone 'utc' at time zone 'est') " .
- "ORDER BY DATE(created_at at time zone 'utc' at time zone 'est') DESC " .
- "LIMIT 30"));
- }
- return view('app/patients', compact('patients', 'filter', 'patientAcquisitionData'));
- }
- public function patientsSuggest(Request $request)
- {
- $pro = $this->pro;
- $term = $request->input('term') ? trim($request->input('term')) : '';
- $originalTerm = $term;
- if (empty($term)) return '';
- // if multiple words in query, check for all (max 2)
- $term2 = '';
- if(strpos($term, ' ') !== FALSE) {
- $terms = explode(' ', $term);
- $term = trim($terms[0]);
- $term2 = trim($terms[1]);
- }
- $phoneNumberTerm = preg_replace("/[^0-9]/", "", $originalTerm );
- if($phoneNumberTerm == ""){ //to avoid search with blank string
- $phoneNumberTerm = $term;
- }
- $clientQuery= Client::whereNull('shadow_pro_id')
- ->where(function ($q) use ($term, $phoneNumberTerm) {
- $q->where('name_first', 'ILIKE', '%' . $term . '%')
- ->orWhere('name_last', 'ILIKE', '%' . $term . '%')
- ->orWhere('cell_number', 'ILIKE', '%' . $phoneNumberTerm . '%')
- ->orWhere('phone_home', 'ILIKE', '%' . $phoneNumberTerm . '%');
- });
- if(!empty($term2)) {
- $clientQuery = $clientQuery->where(function ($q) use ($term2, $phoneNumberTerm) {
- $q->where('name_first', 'ILIKE', '%' . $term2 . '%')
- ->orWhere('name_last', 'ILIKE', '%' . $term2 . '%')
- ->orWhere('cell_number', 'ILIKE', '%' . $phoneNumberTerm . '%')
- ->orWhere('phone_home', 'ILIKE', '%' . $phoneNumberTerm . '%');
- });
- }
- if(!($pro->pro_type === 'ADMIN' && $pro->can_see_any_client_via_search)) {
- $clientQuery->where(function ($q) use ($pro) {
- if($pro->pro_type === 'ADMIN') {
- $q->whereIn('id', $pro->getMyClientIds(true))->orWhereNull('mcp_pro_id');
- }
- else {
- $q->whereIn('id', $pro->getMyClientIds(true));
- }
- });
- }
- $clients = $clientQuery->get();
- return view('app/patient-suggest', compact('clients'));
- }
- public function pharmacySuggest(Request $request)
- {
- $term = $request->input('term') ? trim($request->input('term')) : '';
- if (empty($term)) return '';
- $term = strtolower($term);
- $pharmacies = Facility::where('facility_type', 'Pharmacy')
- ->where(function ($q) use ($term) {
- $q->orWhereRaw('LOWER(name::text) LIKE ?', ['%' . $term . '%'])
- ->orWhereRaw('LOWER(address_line1::text) LIKE ?', ['%' . $term . '%'])
- ->orWhereRaw('LOWER(address_line2::text) LIKE ?', ['%' . $term . '%'])
- ->orWhereRaw('LOWER(address_city::text) LIKE ?', ['%' . $term . '%'])
- ->orWhereRaw('LOWER(address_state::text) LIKE ?', ['%' . $term . '%'])
- ->orWhereRaw('LOWER(phone::text) LIKE ?', ['%' . $term . '%'])
- ->orWhereRaw('LOWER(address_zip::text) LIKE ?', ['%' . $term . '%']);
- });
- if($request->input('city')) {
- $pharmacies = $pharmacies->whereRaw('LOWER(address_city::text) LIKE ?', ['%' . strtolower($request->input('city')) . '%']);
- }
- if($request->input('state')) {
- $pharmacies = $pharmacies->whereRaw('LOWER(address_state::text) LIKE ?', ['%' . strtolower($request->input('state')) . '%']);
- }
- if($request->input('zip')) {
- $pharmacies = $pharmacies->whereRaw('LOWER(address_zip::text) LIKE ?', ['%' . strtolower($request->input('zip')) . '%']);
- }
- $pharmacies = $pharmacies
- ->orderBy('name', 'asc')
- ->orderBy('address_line1', 'asc')
- ->orderBy('address_city', 'asc')
- ->orderBy('address_state', 'asc')
- ->get();
- return view('app/pharmacy-suggest', compact('pharmacies'));
- }
- public function facilitySuggestJSON(Request $request)
- {
- $term = $request->input('term') ? trim($request->input('term')) : '';
- if (empty($term)) return '';
- $terms = explode(' ', $term);
- $terms = array_filter($terms, function($_x) {
- return !!trim($_x);
- });
- $whereCondition = [];
- $whereParams = [];
- for ($i = 0; $i < count($terms); $i++) {
- $whereCondition[] = "(name ILIKE :term{$i} OR address_city ILIKE :term{$i} OR address_state ILIKE :term{$i} OR address_zip ILIKE :term{$i})";
- $whereParams["term{$i}"] = '%' . $terms[$i] . '%';
- }
- $whereCondition = implode(" AND ", $whereCondition);
- $matches = DB::select(
- "SELECT (name || ' ' || address_city || ' ' || address_state || ' ' || address_zip) as text,
- address_line1 as text2,
- name, address_city as city, address_state as state, address_zip as zip, phone, fax FROM facility
- WHERE {$whereCondition} ORDER BY name", $whereParams);
- return json_encode([
- "success" => true,
- "data" => $matches
- ]);
- }
- public function proSuggest(Request $request) {
- $term = $request->input('term') ? trim($request->input('term')) : '';
- if (empty($term)) return '';
- $term = strtolower($term);
- $pros = Pro::where(function ($q) use ($term) {
- $q->orWhereRaw('LOWER(name_first::text) LIKE ?', ['%' . $term . '%'])
- ->orWhereRaw('LOWER(name_last::text) LIKE ?', ['%' . $term . '%'])
- ->orWhereRaw('cell_number LIKE ?', ['%' . $term . '%']);
- });
- $type = $request->input('type') ? trim($request->input('type')) : '';
- if(!!$type) {
- switch(strtolower($type)) {
- case 'hcp':
- $pros->where('is_hcp', true);
- break;
- case 'default-na': // TODO: fix condition for NA
- $pros->where('is_hcp', false)->where('pro_type', '!=', 'ADMIN');
- break;
- case 'admin':
- $pros->where('pro_type', 'ADMIN');
- break;
- case 'non-admin':
- $pros->where('pro_type', '!=', 'ADMIN');
- break;
- }
- }
- if($this->performer->pro && $this->performer->pro->pro_type != 'ADMIN'){
- $accessiblePros = ProProAccess::where('owner_pro_id', $this->performer->pro->id);
- $accessibleProIds = [];
- foreach($accessiblePros as $accessiblePro){
- $accessibleProIds[] = $accessiblePro->id;
- }
- $accessibleProIds[] = $this->performer->pro->id;
- // for dna, add pros accessible via pro teams
- if($this->performer->pro->isDefaultNA()) {
- $teams = $this->performer->pro->teamsWhereAssistant;
- foreach ($teams as $team) {
- if(!in_array($team->mcp_pro_id, $accessibleProIds)) {
- $accessibleProIds[] = $team->mcp_pro_id;
- }
- }
- }
- $pros->whereIn('id', $accessibleProIds);
- }
- $suggestedPros = $pros->orderBy('name_last')->orderBy('name_first')->get();
- // for calendar select2
- if($request->input('json')) {
- $jsonPros = $suggestedPros->map(function($_pro) {
- return [
- "uid" => $_pro->uid,
- "id" => $_pro->id,
- "text" => $_pro->displayName(),
- "initials" => $_pro->initials(),
- ];
- });
- return json_encode([
- "results" => $jsonPros
- ]);
- }
- return view('app/pro-suggest', compact('suggestedPros'));
- }
- public function canAccessPatient(Request $request, $uid) {
- return json_encode([
- "success" => true,
- "data" => $this->performer->pro->canAccess($uid)
- ]);
- }
- public function proDisplayName(Request $request, Pro $pro) {
- return $pro ? $pro->displayName() : '';
- }
- public function unmappedSMS(Request $request, $filter = '')
- {
- $proID = $this->performer()->pro->id;
- if ($this->performer()->pro->pro_type === 'ADMIN') {
- $query = Client::where('id', '>', 0);
- } else {
- $query = Client::where(function ($q) use ($proID) {
- $q->where('mcp_pro_id', $proID)
- ->orWhere('cm_pro_id', $proID)
- ->orWhere('rmm_pro_id', $proID)
- ->orWhere('rme_pro_id', $proID)
- ->orWhereRaw('id IN (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = ?)', [$proID]);
- });
- }
- $patients = $query->orderBy('name_last', 'asc')->orderBy('name_first', 'asc')->get();
- $unmappedSMS = ClientSMS::where('client_id', null)->where('incoming_or_outgoing', 'INCOMING')->paginate(20);
- return view('app/unmapped-sms', compact('unmappedSMS', 'patients'));
- }
- public function newPatient(Request $request)
- {
- $mbPayers = MBPayer::all();
- return view('app/new-patient', compact('mbPayers'));
- }
- public function newNonMcnPatient(Request $request)
- {
- $mbPayers = MBPayer::all();
- return view('app/new-non-mcn-patient', compact('mbPayers'));
- }
- public function mc(Request $request, $fragment = "")
- {
- $page = "/";
- if ($fragment) {
- $page = '/' . $fragment;
- }
- return view('app/mc', compact('page'));
- }
- public function blank(Request $request)
- {
- return view('app/blank');
- }
- public function noteTemplateSet(Request $request, $section, $template)
- {
- return view('app/patient/note/_template', [
- "sectionInternalName" => $section,
- "templateName" => $template
- ]);
- }
- public function noteExamTemplateSet(Request $request, $exam, $template)
- {
- return view('app/patient/note/_template-exam', [
- "exam" => $exam,
- "sectionInternalName" => 'exam-' . $exam . '-detail',
- "templateName" => $template
- ]);
- }
- public function logInAs(Request $request)
- {
- if($this->pro->pro_type != 'ADMIN'){
- return redirect()->to(route('dashboard'));
- }
- // dummy condition to get the chain-ability going
- $pros = Pro::where('id', '>', 0);
- if($request->input('q')) {
- $nameQuery = '%' . $request->input('q') . '%';
- $pros = $pros->where(function ($query) use ($nameQuery) {
- $query->where('name_first', 'ILIKE', $nameQuery)
- ->orWhere('name_last', 'ILIKE', $nameQuery)
- ->orWhere('email_address', 'ILIKE', $nameQuery)
- ->orWhere('cell_number', 'ILIKE', $nameQuery);
- });
- }
- if($request->input('sort') && $request->input('dir')) {
- $pros = $pros->orderBy($request->input('sort'), $request->input('dir'));
- }
- else {
- $pros = $pros->orderBy('name_last', 'asc');
- }
- $pros = $pros->paginate(20);
- return view('app/log-in-as', ['logInAsPros' => $pros]);
- }
- public function processLogInAs(Request $request)
- {
- $api = new Backend();
- try {
- $apiResponse = $api->post('session/proLogInAs', [
- 'proUid' => $request->post('proUid')
- ],
- [
- 'sessionKey'=>$this->performer()->session_key
- ]);
- $data = json_decode($apiResponse->getContents());
- if (!property_exists($data, 'success') || !$data->success) {
- return redirect()->to(route('log-in-as'))->with('message', $data->message)
- ->withInput($request->input());
- }
- Cookie::queue('sessionKey', $data->data->sessionKey);
- return redirect('/mc');
- } catch (\Exception $e) {
- return redirect()->to(route('log-in-as'))
- ->with('message', 'Unable to process your request at the moment. Please try again later.')
- ->withInput($request->input());
- }
- }
- public function backToAdminPro(Request $request){
- $adminPerformerId = $this->performer->logged_in_as_pro_from_admin_pro_app_session_id;
- $adminPerformer = AppSession::where('id', $adminPerformerId)->first();
- $url = "/session/pro_log_in_with_session_key/".$adminPerformer->session_key;
- $api = new Backend();
- try {
- $apiResponse = $api->post($url, []);
- $data = json_decode($apiResponse->getContents());
- if (!property_exists($data, 'success') || !$data->success) {
- return redirect()->to(route('logout'));
- }
- Cookie::queue('sessionKey', $data->data->sessionKey);
- return redirect(route('dashboard'));
- } catch (\Exception $e) {
- return redirect(route('dashboard'));
- }
- }
- public function getTicket(Request $request, Ticket $ticket) {
- $ticket->data = json_decode($ticket->data);
- // $ticket->created_at = friendly_date_time($ticket->created_at);
- $ticket->assignedPro;
- $ticket->managerPro;
- $ticket->orderingPro;
- $ticket->initiatingPro;
- return json_encode($ticket);
- }
- public function genericBill(Request $request, $entityType, $entityUid) {
- $patient = null;
- if ($entityType && $entityUid) {
- try {
- $entityClass = "\\App\\Models\\" . $entityType;
- $entity = $entityClass::where('uid', $entityUid)->first();
- if ($entity->client) {
- $patient = $entity->client;
- }
- } catch (\Exception $e) {
- }
- }
- return view('app.generic-bills.inline', ['class' => 'p-3 border-top mt-3', 'entityType' => $entityType, 'entityUid' => $entityUid, 'patient' => $patient]);
- }
- }
|