PracticeManagementController.php 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Models\AppSession;
  4. use App\Models\BillingReport;
  5. use App\Models\CareMonth;
  6. use App\Models\ClaimEDI;
  7. use App\Models\Handout;
  8. use App\Models\MBClaim;
  9. use App\Models\Measurement;
  10. use App\Models\Bill;
  11. use App\Models\Claim;
  12. use App\Models\Client;
  13. use App\Models\McpRequest;
  14. use App\Models\Note;
  15. use App\Models\Pack;
  16. use App\Models\Pro;
  17. use App\Models\Product;
  18. use App\Models\ProFavorite;
  19. use App\Models\ProGeneralAvailability;
  20. use App\Models\ProProAccess;
  21. use App\Models\ProRate;
  22. use App\Models\ProSpecificAvailability;
  23. use App\Models\ProSpecificUnavailability;
  24. use App\Models\ProTextShortcut;
  25. use App\Models\ProTransaction;
  26. use App\Models\Shipment;
  27. use App\Models\SupplyOrder;
  28. use App\Models\Ticket;
  29. use App\Models\ClientMeasurementDaysPerMonth;
  30. use Illuminate\Support\Facades\DB;
  31. use Illuminate\Support\Facades\Http;
  32. use PDF;
  33. use DateTime;
  34. use DateTimeZone;
  35. use Illuminate\Http\Request;
  36. class PracticeManagementController extends Controller
  37. {
  38. public function remoteMonitoringReport(Request $request)
  39. {
  40. $rows = null;
  41. $proID = $this->performer()->pro->id;
  42. $isAdmin = $this->performer()->pro->pro_type == 'ADMIN';
  43. $rows = $isAdmin ? ClientMeasurementDaysPerMonth::all() : ClientMeasurementDaysPerMonth::where('mcp_pro_id', $proID)->orderBy('year_month', 'asc')->orderBy('num_of_days_with_measurement', 'asc')->get();
  44. return view ('app.practice-management.remote-monitoring-report', compact('rows'));
  45. }
  46. public function billingReport(Request $request)
  47. {
  48. $rows = BillingReport::paginate(50);
  49. return view('app.practice-management.billing-report', compact('rows'));
  50. }
  51. public function dashboard(Request $request)
  52. {
  53. return view('app.practice-management.dashboard');
  54. }
  55. public function rates(Request $request, $selectedProUid = 'all')
  56. {
  57. $proUid = $selectedProUid ? $selectedProUid : 'all';
  58. $rates = ProRate::where('is_active', true);
  59. if ($proUid !== 'all') {
  60. $selectedPro = Pro::where('uid', $proUid)->first();
  61. $rates = $rates->where('pro_id', $selectedPro->id);
  62. }
  63. $rates = $rates->orderBy('pro_id', 'asc')->get();
  64. $pros = $this->pros;
  65. return view('app.practice-management.rates', compact('rates', 'pros', 'selectedProUid'));
  66. }
  67. public function previousBills(Request $request)
  68. {
  69. return view('app.practice-management.previous-bills');
  70. }
  71. public function financialTransactions(Request $request)
  72. {
  73. $transactions = ProTransaction::where('pro_id', $this->performer()->pro->id)->orderBy('created_at', 'desc')->get();
  74. return view('app.practice-management.financial-transactions', compact('transactions'));
  75. }
  76. public function pendingBillsToSign(Request $request)
  77. {
  78. return view('app.practice-management.pending-bills-to-sign');
  79. }
  80. public function HR(Request $request)
  81. {
  82. return view('app.practice-management.hr');
  83. }
  84. public function directDepositSettings(Request $request)
  85. {
  86. return view('app.practice-management.direct-deposit-settings');
  87. }
  88. public function w9(Request $request)
  89. {
  90. return view('app.practice-management.w9');
  91. }
  92. public function contract(Request $request)
  93. {
  94. return view('app.practice-management.contract');
  95. }
  96. public function notes(Request $request, $filter = '')
  97. {
  98. $proID = $this->performer()->pro->id;
  99. $query = Note::where('hcp_pro_id', $proID);
  100. switch ($filter) {
  101. case 'not-yet-signed':
  102. $query = $query->where('is_signed_by_hcp', false);
  103. break;
  104. case 'not-yet-signed-but-ally-signed':
  105. $query = $query->where('is_signed_by_hcp', false)->where('is_signed_by_ally', true);
  106. break;
  107. case 'without-bills':
  108. $query = $query->where('is_signed_by_hcp', true)->where('is_cancelled', false)->whereDoesntHave('bills');
  109. break;
  110. // more cases can be added as needed
  111. default:
  112. break;
  113. }
  114. $notes = $query->orderBy('created_at', 'desc')->get();
  115. return view('app.practice-management.notes', compact('notes', 'filter'));
  116. }
  117. public function naBillableSignedNotes(Request $request)
  118. {
  119. $notes = Note
  120. ::where('is_signed_by_hcp', TRUE)
  121. ->where('ally_pro_id', $this->performer()->pro->id)
  122. ->where('is_cancelled', FALSE)
  123. ->whereRaw("
  124. (
  125. SELECT count(bill.id)
  126. FROM bill WHERE
  127. bill.is_cancelled = FALSE AND
  128. bill.generic_pro_id = {$this->performer()->pro->id} AND
  129. bill.note_id = note.id
  130. ) = 0
  131. ");
  132. $notes = $notes->orderBy('created_at', 'desc')->get();
  133. return view('app.practice-management.na-billable-signed-notes', compact('notes'));
  134. }
  135. public function bills(Request $request, $filter = '')
  136. {
  137. $proID = $this->performer()->pro->id;
  138. $query = Bill::where('is_cancelled', false)->where('bill_service_type', '<>', 'CARE_MONTH');
  139. switch ($filter) {
  140. case 'not-yet-signed':
  141. $query = $query
  142. ->where(function ($q) use ($proID) {
  143. $q->where(function ($q2) use ($proID) {
  144. $q2->where('hcp_pro_id', $proID)->where('is_signed_by_hcp', false);
  145. })
  146. ->orWhere(function ($q2) use ($proID) {
  147. $q2->where('cm_pro_id', $proID)->where('is_signed_by_cm', false);
  148. })
  149. ->orWhere(function ($q2) use ($proID) {
  150. $q2->where('rme_pro_id', $proID)->where('is_signed_by_rme', false);
  151. })
  152. ->orWhere(function ($q2) use ($proID) {
  153. $q2->where('rmm_pro_id', $proID)->where('is_signed_by_rmm', false);
  154. });
  155. });
  156. break;
  157. case 'previous':
  158. $query = $query
  159. ->where(function ($q) use ($proID) {
  160. $q->where(function ($q2) use ($proID) {
  161. $q2->where('hcp_pro_id', $proID)->where('is_signed_by_hcp', true);
  162. })
  163. ->orWhere(function ($q2) use ($proID) {
  164. $q2->where('cm_pro_id', $proID)->where('is_signed_by_cm', true);
  165. })
  166. ->orWhere(function ($q2) use ($proID) {
  167. $q2->where('rme_pro_id', $proID)->where('is_signed_by_rme', true);
  168. })
  169. ->orWhere(function ($q2) use ($proID) {
  170. $q2->where('rmm_pro_id', $proID)->where('is_signed_by_rmm', true);
  171. });
  172. });
  173. break;
  174. // more cases can be added as needed
  175. default:
  176. break;
  177. }
  178. $bills = $query->orderBy('created_at', 'desc')->get();
  179. return view('app.practice-management.bills', compact('bills', 'filter'));
  180. }
  181. public function unacknowledgedCancelledBills(Request $request)
  182. {
  183. $bills = Bill::where('hcp_pro_id', $this->performer()->pro->id)
  184. ->where('is_cancelled', true)
  185. ->where('is_cancellation_acknowledged', false)
  186. ->orderBy('created_at', 'desc')
  187. ->get();
  188. return view('app.practice-management.unacknowledged-cancelled-bills', compact('bills'));
  189. }
  190. public function myTickets(Request $request, $filter = 'open')
  191. {
  192. $performer = $this->performer();
  193. $myTickets = Ticket::where(function ($q) use ($performer) {
  194. $q->where('assigned_pro_id', $performer->pro_id)
  195. ->orWhere('manager_pro_id', $performer->pro_id)
  196. ->orWhere('ordering_pro_id', $performer->pro_id)
  197. ->orWhere('initiating_pro_id', $performer->pro_id);
  198. });
  199. if ($filter === 'open') {
  200. $myTickets = $myTickets->where('is_open', true);
  201. } else if ($filter === 'closed') {
  202. $myTickets = $myTickets->where('is_open', false);
  203. }
  204. $myTickets = $myTickets->orderBy('created_at', 'desc')->get();
  205. return view('app.practice-management.my-tickets', compact('myTickets', 'filter'));
  206. }
  207. public function myTextShortcuts(Request $request)
  208. {
  209. $myTextShortcuts = DB::table('pro_text_shortcut')
  210. ->leftJoin('pro', 'pro_text_shortcut.pro_id', '=', 'pro.id')
  211. ->select(
  212. 'pro_text_shortcut.uid',
  213. 'pro_text_shortcut.shortcut',
  214. 'pro_text_shortcut.text',
  215. 'pro.name_first',
  216. 'pro.name_last'
  217. )
  218. ->where('pro_text_shortcut.is_removed', false);
  219. if($this->performer()->pro->pro_type !== 'ADMIN') {
  220. $myTextShortcuts = $myTextShortcuts->where('pro_id', $this->performer()->pro_id);
  221. }
  222. $myTextShortcuts = $myTextShortcuts
  223. ->orderBy('pro.name_last')
  224. ->orderBy('pro.name_first')
  225. ->get();
  226. return view('app.practice-management.my-text-shortcuts', compact('myTextShortcuts'));
  227. }
  228. public function myFavorites(Request $request, $filter = 'all')
  229. {
  230. $performer = $this->performer();
  231. $myFavorites = ProFavorite::where('pro_id', $performer->pro_id)
  232. ->where('is_removed', false);
  233. if ($filter !== 'all') {
  234. $myFavorites = $myFavorites->where('category', $filter);
  235. }
  236. $myFavorites = $myFavorites
  237. ->orderBy('category', 'asc')
  238. ->orderBy('position_index', 'asc')
  239. ->get();
  240. return view('app.practice-management.my-favorites', compact('myFavorites', 'filter'));
  241. }
  242. public function proAvailability(Request $request, $proUid = null)
  243. {
  244. $performer = $this->performer();
  245. $pro = $performer->pro;
  246. if ($proUid) {
  247. $pro = Pro::where('uid', $proUid)->first();
  248. }
  249. if ($request->get('pro_uid')) {
  250. $proUid = $request->get('pro_uid');
  251. $pro = Pro::where('uid', $proUid)->first();
  252. }
  253. $selectedProUid = $pro->uid;
  254. $pros = $this->pros;
  255. $generalAvailabilitiesList = ProGeneralAvailability::where('pro_id', $pro->id)->where('is_cancelled', false)->orderBy('created_at', 'asc')->get();
  256. $generalAvailabilities = [
  257. 'MONDAY' => [],
  258. 'TUESDAY' => [],
  259. 'WEDNESDAY' => [],
  260. 'THURSDAY' => [],
  261. 'FRIDAY' => [],
  262. 'SATURDAY' => [],
  263. 'SUNDAY' => [],
  264. ];
  265. foreach ($generalAvailabilitiesList as $ga) {
  266. if ($ga->day_of_week == 'MONDAY') {
  267. $generalAvailabilities['MONDAY'][] = $ga;
  268. }
  269. if ($ga->day_of_week == 'TUESDAY') {
  270. $generalAvailabilities['TUESDAY'][] = $ga;
  271. }
  272. if ($ga->day_of_week == 'WEDNESDAY') {
  273. $generalAvailabilities['WEDNESDAY'][] = $ga;
  274. }
  275. if ($ga->day_of_week == 'THURSDAY') {
  276. $generalAvailabilities['THURSDAY'][] = $ga;
  277. }
  278. if ($ga->day_of_week == 'FRIDAY') {
  279. $generalAvailabilities['FRIDAY'][] = $ga;
  280. }
  281. if ($ga->day_of_week == 'SATURDAY') {
  282. $generalAvailabilities['SATURDAY'][] = $ga;
  283. }
  284. if ($ga->day_of_week == 'SUNDAY') {
  285. $generalAvailabilities['SUNDAY'][] = $ga;
  286. }
  287. }
  288. $specificAvailabilities = ProSpecificAvailability::where('pro_id', $pro->id)->where('is_cancelled', false)->orderBy('start_time')->get();
  289. $specificUnavailabilities = ProSpecificUnavailability::where('pro_id', $pro->id)->where('is_cancelled', false)->orderBy('start_time', 'asc')->get();
  290. //events for the calendar
  291. $startDate = date('Y-m-d', strtotime("sunday -1 week"));
  292. $endDateTime = new DateTime($startDate);
  293. $endDateTime->modify('+6 day');
  294. $endDate = $endDateTime->format("Y-m-d");
  295. $eventsData = $pro->getAvailabilityEvents($startDate, $endDate);
  296. $events = json_encode($eventsData);
  297. return view(
  298. 'app.practice-management.pro-availability',
  299. compact(
  300. 'pros',
  301. 'generalAvailabilities',
  302. 'specificAvailabilities',
  303. 'specificUnavailabilities',
  304. 'events',
  305. 'selectedProUid'
  306. )
  307. );
  308. }
  309. public function loadAvailability(Request $request, $proUid)
  310. {
  311. $performer = $this->performer();
  312. $pro = $performer->pro;
  313. $startDate = $request->get('start');
  314. $endDate = $request->get('end');
  315. $selectedPro = Pro::where('uid', $proUid)->first();
  316. return $selectedPro->getAvailabilityEvents($startDate, $endDate);
  317. }
  318. public function proAvailabilityFilter(Request $request)
  319. {
  320. $proUid = $request->get('proUid');
  321. return ['success' => true, 'data' => $proUid];
  322. }
  323. // video call page (RHS)
  324. // generic call handle (no uid)
  325. // specific call handle (uid of client)
  326. public function meet(Request $request, $uid = false)
  327. {
  328. $session = AppSession::where('session_key', $request->cookie('sessionKey'))->first();
  329. $client = !empty($uid) ? Client::where('uid', $uid)->first() : null;
  330. if (!empty($client)) {
  331. return view('app.video.call-minimal', compact('session', 'client'));
  332. }
  333. return view('app.video.call-agora-v2', compact('session', 'client'));
  334. }
  335. // check video page
  336. public function checkVideo(Request $request, $uid)
  337. {
  338. $session = AppSession::where('session_key', $request->cookie('sessionKey'))->first();
  339. $client = !empty($uid) ? Client::where('uid', $uid)->first() : null;
  340. $publish = false;
  341. return view('app.video.check-video-minimal', compact('session', 'client'));
  342. }
  343. public function getParticipantInfo(Request $request)
  344. {
  345. $sid = intval($request->get('uid')) - 1000000;
  346. $session = AppSession::where('id', $sid)->first();
  347. $result = [
  348. "type" => '',
  349. "name" => ''
  350. ];
  351. if ($session) {
  352. $result["type"] = $session->session_type;
  353. switch ($session->session_type) {
  354. case 'PRO':
  355. $pro = Pro::where('id', $session->pro_id)->first();
  356. $result["name"] = $pro->displayName();
  357. break;
  358. case 'CLIENT':
  359. $client = Client::where('id', $session->client_id)->first();
  360. $result["name"] = $client->displayName();
  361. break;
  362. }
  363. }
  364. return json_encode($result);
  365. }
  366. // ajax ep used by the video page
  367. // this is needed bcoz meet() is used not
  368. // just for the client passed to the view
  369. public function getOpentokSessionKey(Request $request, $uid)
  370. {
  371. $client = Client::where('uid', $uid)->first();
  372. return json_encode(["data" => $client ? $client->opentok_session_id : '']);
  373. }
  374. // poll to check if there are patients with active mcp requests
  375. public function getPatientsInQueue(Request $request)
  376. {
  377. $myInitiatives = $this->performer->pro->initiatives;
  378. if ($myInitiatives) {
  379. $myInitiatives = strtoupper($myInitiatives);
  380. }
  381. $myInitiativesList = explode('|', $myInitiatives);
  382. $myForeignLanguages = $this->performer->pro->foreign_languages;
  383. if ($myForeignLanguages) {
  384. $myForeignLanguages = strtoupper($myForeignLanguages);
  385. }
  386. $myForeignLanguagesList = explode('|', $myForeignLanguages);
  387. $clients = Client::whereNotNull('active_mcp_request_id')->where(function ($query) use ($myInitiativesList) {
  388. $query->whereNull('initiative')->orWhereIn('initiative', $myInitiativesList);
  389. })
  390. ->where(function ($query) use ($myForeignLanguagesList) {
  391. $query->whereNull('preferred_foreign_language')->orWhereIn('preferred_foreign_language', $myForeignLanguagesList);
  392. })->limit(3)->get();
  393. $results = [];
  394. foreach ($clients as $client) {
  395. $results[] = [
  396. 'clientUid' => $client->uid,
  397. 'name' => $client->displayName(),
  398. 'initials' => substr($client->name_first, 0, 1) . substr($client->name_last, 0, 1)
  399. ];
  400. }
  401. return json_encode($results);
  402. }
  403. public function currentWork(Request $request)
  404. {
  405. return view('app/current-work');
  406. }
  407. public function calendar(Request $request, $proUid = null)
  408. {
  409. $pros = Pro::all();
  410. if ($this->pro && $this->pro->pro_type != 'ADMIN') {
  411. $accessiblePros = ProProAccess::where('owner_pro_id', $this->pro->id);
  412. $accessibleProIds = [];
  413. foreach ($accessiblePros as $accessiblePro) {
  414. $accessibleProIds[] = $accessiblePro->id;
  415. }
  416. $accessibleProIds[] = $this->pro->id;
  417. $pros = Pro::whereIn('id', $accessibleProIds)->get();
  418. }
  419. return view('app.practice-management.calendar', compact('pros'));
  420. }
  421. public function cellularDeviceManager(Request $request, $proUid = null)
  422. {
  423. $proUid = $proUid ? $proUid : $request->get('pro-uid');
  424. $performerPro = $this->performer->pro;
  425. $targetPro = null;
  426. $allPros = [];
  427. $expectedForHcp = null;
  428. if ($performerPro->pro_type == 'ADMIN') {
  429. $allPros = Pro::all();
  430. $targetPro = Pro::where('uid', $proUid)->first();
  431. } else {
  432. $targetPro = $performerPro;
  433. }
  434. $clients = [];
  435. if ($targetPro) {
  436. $clients = Client::where('mcp_pro_id', $targetPro->id)->orderBy('created_at', 'desc')->paginate(100);
  437. } else {
  438. $clients = Client::orderBy('created_at', 'desc')->paginate(100);
  439. }
  440. return view('app.practice-management.cellular-device-manager', compact('clients', 'allPros', 'targetPro', 'proUid'));
  441. }
  442. public function treatmentServiceUtil(Request $request)
  443. {
  444. $view_treatment_service_utilization_org = DB::select(DB::raw("SELECT * FROM view_treatment_service_utilization_org ORDER BY effective_date DESC"));
  445. $view_treatment_service_utilization = DB::select(DB::raw("SELECT * FROM view_treatment_service_utilization ORDER BY effective_date DESC, total_hrs DESC"));
  446. $view_treatment_service_utilization_by_patient = DB::select(DB::raw("SELECT * FROM view_treatment_service_utilization_by_patient ORDER BY pro_lname ASC, pro_fname ASC, hcp_pro_id ASC, total_hrs DESC"));
  447. return view('app.practice-management.treatment-services-util', compact(
  448. 'view_treatment_service_utilization_org',
  449. 'view_treatment_service_utilization',
  450. 'view_treatment_service_utilization_by_patient'));
  451. }
  452. public function processingBillMatrix(Request $request, $proUid = null)
  453. {
  454. $proUid = $proUid ? $proUid : $request->get('pro-uid');
  455. $performerPro = $this->performer->pro;
  456. $targetPro = null;
  457. if ($performerPro->pro_type == 'ADMIN') {
  458. $targetPro = Pro::where('uid', $proUid)->first();
  459. } else {
  460. $targetPro = $performerPro;
  461. }
  462. $bills = Bill::where('is_cancelled', false);
  463. if(!$request->input('t') || $request->input('t') === 'hcp') {
  464. $bills = $bills
  465. ->where('has_hcp_been_paid', false)
  466. ->where('is_signed_by_hcp', true);
  467. if ($targetPro) {
  468. $bills = $bills->where('hcp_pro_id', $targetPro->id);
  469. }
  470. }
  471. else if($request->input('t') === 'na') {
  472. $bills = $bills
  473. ->where('has_generic_pro_been_paid', false)
  474. ->where('is_signed_by_generic_pro', true);
  475. if ($targetPro) {
  476. $bills = $bills->where('generic_pro_id', $targetPro->id);
  477. }
  478. }
  479. $filter = $request->input('f');
  480. switch ($filter) {
  481. case 'verified':
  482. $bills = $bills->where('is_verified', true);
  483. break;
  484. case 'not-verified':
  485. $bills = $bills->where('is_verified', false);
  486. break;
  487. }
  488. $bills = $bills->orderBy('effective_date', 'desc')->paginate();
  489. $viewData = [
  490. 'bills' => $bills,
  491. 'targetPro' => $targetPro,
  492. 'performerPro' => $performerPro,
  493. 'proUid' => $proUid
  494. ];
  495. return view('app.practice-management.processing-bill-matrix', $viewData);
  496. }
  497. public function hcpBillMatrix(Request $request, $proUid = null)
  498. {
  499. $proUid = $proUid ? $proUid : $request->get('pro-uid');
  500. $performerPro = $this->performer->pro;
  501. $targetPro = null;
  502. $allPros = [];
  503. $expectedForHcp = null;
  504. if ($performerPro->pro_type == 'ADMIN') {
  505. $allPros = Pro::all();
  506. $targetPro = Pro::where('uid', $proUid)->first();
  507. } else {
  508. $targetPro = $performerPro;
  509. }
  510. $rows = [];
  511. if ($targetPro) {
  512. $rows = DB::select(DB::raw("SELECT * FROM aemish_bill_report WHERE hcp_pro_id = :targetProID"), ['targetProID' => $targetPro->id]);
  513. } else {
  514. $rows = DB::select(DB::raw("SELECT * FROM aemish_bill_report"));
  515. }
  516. return view('app.practice-management.hcp-bill-matrix', compact('rows', 'allPros', 'expectedForHcp', 'targetPro', 'proUid'));
  517. }
  518. public function billingManager(Request $request, $proUid = null)
  519. {
  520. $proUid = $proUid ? $proUid : $request->get('pro-uid');
  521. $performerPro = $this->performer->pro;
  522. $targetPro = null;
  523. $allPros = [];
  524. $expectedForHcp = null;
  525. if ($performerPro->pro_type == 'ADMIN') {
  526. $allPros = Pro::all();
  527. $targetPro = Pro::where('uid', $proUid)->first();
  528. } else {
  529. $targetPro = $performerPro;
  530. }
  531. $notes = [];
  532. if ($targetPro) {
  533. $expectedForHcp = DB::select(DB::raw("SELECT coalesce(SUM(hcp_expected_payment_amount),0) as expected_pay FROM bill WHERE hcp_pro_id = :targetProID AND is_signed_by_hcp IS TRUE AND is_cancelled = false"), ['targetProID' => $targetPro->id])[0]->expected_pay;
  534. $notes = Note::where('hcp_pro_id', $targetPro->id);
  535. } else {
  536. $notes = Note::where('id', '>', 0);
  537. }
  538. if($request->input('date')) {
  539. $notes = $notes->where('effective_dateest', $request->input('date'));
  540. }
  541. $filters = [];
  542. $filters['bills_created'] = $request->input('bills_created');
  543. $filters['is_billing_marked_done'] = $request->input('is_billing_marked_done');
  544. $filters['bills_resolved'] = $request->input('bills_resolved');
  545. $filters['bills_closed'] = $request->input('bills_closed');
  546. $filters['claims_created'] = $request->input('claims_created');
  547. $filters['claims_closed'] = $request->input('claims_closed');
  548. if ($filters['bills_created']) {
  549. $notes->where(
  550. 'bill_total_expected',
  551. ($filters['bills_created'] === 'yes' ? '>' : '<='),
  552. 0);
  553. }
  554. if ($filters['is_billing_marked_done']) {
  555. $notes->where(
  556. 'is_billing_marked_done',
  557. ($filters['is_billing_marked_done'] === 'yes' ? '=' : '!='),
  558. true);
  559. }
  560. if ($filters['bills_resolved']) {
  561. $notes->whereRaw('(SELECT count(id) FROM bill WHERE note_id = note.id) > 0'); // have bills
  562. if ($filters['bills_resolved'] === 'yes') {
  563. $notes->whereRaw('(SELECT count(id) FROM bill WHERE note_id = note.id AND (is_cancelled = false AND is_verified = false) OR (is_cancelled = TRUE AND is_cancellation_acknowledged = FALSE)) > 0');
  564. } elseif ($filters['bills_resolved'] === 'no') {
  565. $notes->whereRaw('(SELECT count(id) FROM bill WHERE note_id = note.id AND ((is_cancelled = true AND is_cancellation_acknowledged = true) OR is_verified = true)) = 0');
  566. }
  567. }
  568. if ($filters['bills_closed']) {
  569. $notes->where(
  570. 'is_bill_closed',
  571. ($filters['bills_closed'] === 'yes' ? '=' : '!='),
  572. true);
  573. }
  574. if ($filters['claims_created']) {
  575. $notes->where(
  576. 'claim_total_expected',
  577. ($filters['claims_created'] === 'yes' ? '>' : '<='),
  578. 0);
  579. }
  580. if ($filters['claims_closed']) {
  581. $notes->where(
  582. 'is_claim_closed',
  583. ($filters['claims_closed'] === 'yes' ? '=' : '!='),
  584. true);
  585. }
  586. $notes = $notes->orderBy('effective_dateest', 'desc')->paginate(10);
  587. return view('app.practice-management.billing-manager', compact('notes', 'allPros', 'expectedForHcp', 'targetPro', 'proUid', 'filters'));
  588. }
  589. public function remoteMonitoring(Request $request) {
  590. $performer = $this->performer();
  591. $ym = ($request->input('y') ?: 'Y') . '-' . ($request->input('m') ?: 'm');
  592. $careMonthStart = date($ym . '-01');
  593. // filters
  594. $filters = '';
  595. $fmd = $request->input('fmd');
  596. if($fmd && $fmd !== 'all') {
  597. switch($fmd) {
  598. case 'lt16':
  599. $filters .= ' AND care_month.number_of_days_with_remote_measurements < 16 ';
  600. break;
  601. case 'gte16':
  602. $filters .= ' AND care_month.number_of_days_with_remote_measurements >= 16 ';
  603. break;
  604. }
  605. }
  606. $fcomm = $request->input('fcomm');
  607. if($fcomm && $fcomm !== 'all') {
  608. switch($fcomm) {
  609. case '0':
  610. $filters .= ' AND care_month.has_non_hcp_communicated_to_patient_about_rm = FALSE ';
  611. break;
  612. case '1':
  613. $filters .= ' AND care_month.has_non_hcp_communicated_to_patient_about_rm = TRUE ';
  614. break;
  615. }
  616. }
  617. $patients = DB::select(
  618. DB::raw(
  619. "
  620. SELECT client.name_first, client.name_last, client.uid as client_uid,
  621. care_month.uid as care_month_uid,
  622. care_month.id as care_month_id,
  623. care_month.start_date,
  624. care_month.number_of_days_with_remote_measurements,
  625. care_month.has_non_hcp_communicated_to_patient_about_rm,
  626. care_month.rm_num_measurements_not_stamped_by_mcp,
  627. care_month.rm_num_measurements_not_stamped_by_non_hcp,
  628. care_month.rm_num_measurements_not_stamped_by_rmm,
  629. care_month.rm_num_measurements_not_stamped_by_rme,
  630. client.mcp_pro_id,
  631. client.default_na_pro_id,
  632. client.rmm_pro_id,
  633. client.rme_pro_id,
  634. client.cell_number
  635. FROM care_month join client on care_month.client_id = client.id
  636. WHERE (
  637. (client.mcp_pro_id = {$performer->pro->id})
  638. OR (client.rmm_pro_id = {$performer->pro->id})
  639. OR (client.rme_pro_id = {$performer->pro->id})
  640. OR (client.default_na_pro_id = {$performer->pro->id})
  641. )
  642. AND EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  643. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  644. {$filters}
  645. ORDER BY care_month.number_of_days_with_remote_measurements DESC NULLS LAST, client.name_first ASC, client.name_last ASC
  646. "
  647. )
  648. );
  649. $timestamp = strtotime(date('Y-m-d'));
  650. $daysRemaining = (int)date('t', $timestamp) - (int)date('j', $timestamp);
  651. return view('app.practice-management.remote-monitoring', compact('patients', 'daysRemaining', 'careMonthStart'));
  652. }
  653. public function remoteMonitoringMeasurements(Request $request, CareMonth $careMonth) {
  654. $performer = $this->performer();
  655. date_default_timezone_set('US/Eastern');
  656. $start = strtotime(date($careMonth->start_date));
  657. $end = date_add(date_create(date($careMonth->start_date)), date_interval_create_from_date_string("1 month"))->getTimestamp();
  658. $start *= 1000;
  659. $end *= 1000;
  660. $measurements = DB::select(
  661. DB::raw(
  662. "
  663. SELECT * FROM measurement RIGHT JOIN client on measurement.client_id = client.id
  664. WHERE
  665. client.id = {$careMonth->client_id}
  666. AND measurement.label IS NOT NULL
  667. AND measurement.label NOT IN ('SBP', 'DBP')
  668. AND (measurement.is_cellular_zero = FALSE or measurement.is_cellular_zero IS NULL)
  669. AND measurement.is_removed IS FALSE
  670. AND measurement.client_bdt_measurement_id IS NOT NULL
  671. AND measurement.ts >= {$start} AND measurement.ts < {$end}
  672. AND (
  673. (client.mcp_pro_id = {$performer->pro->id} AND measurement.has_been_stamped_by_mcp IS FALSE)
  674. OR (client.rmm_pro_id = {$performer->pro->id} AND measurement.has_been_stamped_by_rmm IS FALSE)
  675. OR (client.rme_pro_id = {$performer->pro->id} AND measurement.has_been_stamped_by_rme IS FALSE)
  676. OR (client.default_na_pro_id = {$performer->pro->id} AND measurement.has_been_stamped_by_non_hcp IS FALSE)
  677. )
  678. ORDER BY ts DESC
  679. "
  680. )
  681. );
  682. return view('app.practice-management.remote-monitoring-measurements', compact('careMonth', 'measurements'));
  683. }
  684. public function billMatrix(Request $request)
  685. {
  686. $bClients = [];
  687. $bHCPPros = [];
  688. $bNAPros = [];
  689. $filters = [];
  690. $filters['client'] = $request->input('client');
  691. $filters['service'] = $request->input('service');
  692. $filters['hcp'] = $request->input('hcp');
  693. $filters['hcp_paid'] = $request->input('hcp_paid');
  694. $filters['expected_op'] = $request->input('expected_op');
  695. $filters['expected_value'] = $request->input('expected_value');
  696. $filters['paid_op'] = $request->input('paid_op');
  697. $filters['paid_value'] = $request->input('paid_value');
  698. $filters['bal_post_date_op'] = $request->input('bal_post_date_op');
  699. $filters['bal_post_date_value'] = $request->input('bal_post_date_value');
  700. $filters['hcp_sign'] = $request->input('hcp_sign');
  701. $filters['verified'] = $request->input('verified');
  702. $filters['cancelled'] = $request->input('cancelled');
  703. $bills = Bill::orderBy('effective_date')->paginate();
  704. return view('app.practice-management.bill-matrix', compact('bills', 'bClients', 'bHCPPros', 'filters'));
  705. }
  706. public function medicarePartBClaims(Request $request)
  707. {
  708. $medicarePartBOnly = $request->get("medicare_part_b");
  709. $allClaims = Claim::where('was_submitted', false)->orWhere('was_submitted', null)->orderBy('created_at', 'desc')->get();
  710. //Only medicare claims
  711. $claims = [];
  712. foreach ($allClaims as $claim) {
  713. if ($claim->client != null && $claim->client->is_part_b_primary == 'YES' && !$claim->edi) {
  714. $claims[] = $claim;
  715. }
  716. }
  717. $claimEDIs = ClaimEDI::all();
  718. return view('app.practice-management.medicare-partb-claims', compact('claims', 'claimEDIs'));
  719. }
  720. // Generate PDF
  721. public function downloadClaims()
  722. {
  723. $claims = Claim::where('was_submitted', false)->orWhere('was_submitted', null)->orderBy('created_at', 'desc')->limit(100)->get();
  724. view()->share('claims', $claims);
  725. $pdf = PDF::loadView('app.practice-management.claims-pdf', $claims);
  726. return $pdf->download('pdf_file.pdf');
  727. }
  728. public function tickets(Request $request, $proUid = null)
  729. {
  730. $tickets = Ticket::orderBy('created_at', 'desc')->paginate();
  731. return view('app.practice-management.tickets', compact('tickets'));
  732. }
  733. public function supplyOrders(Request $request)
  734. {
  735. // counts
  736. $counts = $this->getSupplyOrderCounts();
  737. // so clients
  738. $soClientIDs = DB::table('supply_order')->select('client_id')->distinct()->get()->toArray();
  739. $soClientIDs = array_map(function ($_x) {
  740. return $_x->client_id;
  741. }, $soClientIDs);
  742. $soClients = Client::whereIn('id', $soClientIDs)->get();
  743. // so products
  744. $soProductIDs = DB::table('supply_order')->select('product_id')->distinct()->get()->toArray();
  745. $soProductIDs = array_map(function ($_x) {
  746. return $_x->product_id;
  747. }, $soProductIDs);
  748. $soProducts = Product::whereIn('id', $soProductIDs)->get();
  749. $filters = [];
  750. $filters['client'] = $request->input('client');
  751. $filters['product'] = $request->input('product');
  752. $filters['reason'] = $request->input('reason');
  753. $filters['cu_memo'] = $request->input('cu_memo');
  754. $filters['pro_sign'] = $request->input('pro_sign');
  755. $filters['client_sign'] = $request->input('client_sign');
  756. $filters['shipment'] = $request->input('shipment');
  757. $filters['lot_number'] = $request->input('lot_number');
  758. $filters['imei'] = $request->input('imei');
  759. $filters['cancelled'] = $request->input('cancelled');
  760. $supplyOrders = SupplyOrder::where('id', '>', 0);
  761. // apply filters
  762. if ($filters['client']) $supplyOrders->where('client_id', $filters['client']);
  763. if ($filters['product']) $supplyOrders->where('product_id', $filters['product']);
  764. if ($filters['reason']) $supplyOrders->where('reason', 'ILIKE', '%' . $filters['reason'] . '%');
  765. if ($filters['cu_memo']) $supplyOrders->where('cu_memo', 'ILIKE', '%' . $filters['cu_memo'] . '%');
  766. if ($filters['pro_sign']) $supplyOrders->where('is_signed_by_pro', ($filters['pro_sign'] === 'signed'));
  767. if ($filters['client_sign']) {
  768. if ($filters['client_sign'] === 'signed')
  769. $supplyOrders->where('is_signed_by_client', true);
  770. elseif ($filters['client_sign'] === 'waived')
  771. $supplyOrders->where('is_client_signature_waived', true);
  772. else
  773. $supplyOrders->where('is_client_signature_waived', false)->where('is_signed_by_client', false);
  774. }
  775. if ($filters['shipment']) {
  776. if ($filters['shipment'] === 'not_cleared_for_shipment')
  777. $supplyOrders->whereNull('shipment_id')->where('is_cleared_for_shipment', false);
  778. elseif ($filters['shipment'] === 'cleared_for_shipment')
  779. $supplyOrders->whereNull('shipment_id')->where('is_cleared_for_shipment', true);
  780. else
  781. $supplyOrders
  782. ->whereNotNull('shipment_id')
  783. ->whereRaw('(SELECT status FROM shipment WHERE id = shipment_id LIMIT 1) = ?', [$filters['shipment']]);
  784. }
  785. if ($filters['lot_number']) $supplyOrders->where('lot_number', 'ILIKE', '%' . $filters['lot_number'] . '%');
  786. if ($filters['imei']) $supplyOrders->where('imei', 'ILIKE', '%' . $filters['imei'] . '%');
  787. if ($filters['cancelled']) $supplyOrders->where('is_cancelled', ($filters['cancelled'] === 'cancelled'));
  788. $supplyOrders = $supplyOrders->orderBy('created_at', 'desc')->paginate();
  789. return view('app.practice-management.supply-orders',
  790. compact('supplyOrders', 'filters',
  791. 'soClients', 'soProducts', 'counts'
  792. )
  793. );
  794. }
  795. public function shipments(Request $request, $filter = null)
  796. {
  797. // counts
  798. $counts = $this->getShipmentCounts();
  799. // so clients
  800. $shClientIDs = DB::table('shipment')->select('client_id')->distinct()->get()->toArray();
  801. $shClientIDs = array_map(function ($_x) {
  802. return $_x->client_id;
  803. }, $shClientIDs);
  804. $shClients = Client::whereIn('id', $shClientIDs)->get();
  805. $shipments = Shipment::where('id', '>', 0);
  806. $filters = [];
  807. $filters['client'] = $request->input('client');
  808. $filters['courier'] = $request->input('courier');
  809. $filters['tracking_num'] = $request->input('tracking_num');
  810. $filters['label'] = $request->input('label');
  811. $filters['status'] = $request->input('status');
  812. $filters['cancelled'] = $request->input('cancelled');
  813. if ($filters['client']) $shipments->where('client_id', $filters['client']);
  814. if ($filters['courier']) $shipments->where('courier', 'ILIKE', '%' . $filters['courier'] . '%');
  815. if ($filters['tracking_num']) $shipments->where('tracking_number', 'ILIKE', '%' . $filters['tracking_num'] . '%');
  816. if ($filters['label']) {
  817. if ($filters['label'] === 'yes')
  818. $shipments->whereNotNull('label_system_file_id');
  819. else
  820. $shipments->whereNull('label_system_file_id');
  821. }
  822. if ($filters['status']) $shipments->where('status', $filters['status']);
  823. if ($filters['cancelled']) $shipments->where('is_cancelled', ($filters['cancelled'] === 'cancelled'));
  824. $shipments = $shipments->orderBy('created_at', 'desc')->paginate();
  825. return view('app.practice-management.shipments', compact('shipments', 'filters', 'shClients', 'counts'));
  826. }
  827. public function cellularMeasurements(Request $request)
  828. {
  829. $measurements = Measurement::orderBy('ts', 'desc')->whereNotNull('ts')->paginate();
  830. return view('app.practice-management.cellular-measurements', compact('measurements'));
  831. }
  832. // v2 supply-orders & shipments management (wh)
  833. public function supplyOrdersReadyToShip(Request $request)
  834. {
  835. $counts = $this->getSupplyOrderCounts();
  836. $supplyOrders = SupplyOrder
  837. ::where('is_cleared_for_shipment', true)
  838. ->where('is_cancelled', false)
  839. ->whereNull('shipment_id')
  840. ->join('client', 'client.id', '=', 'supply_order.client_id')
  841. ->orderBy('client.name_last', 'ASC')
  842. ->orderBy('client.name_first', 'ASC')
  843. ->orderBy('supply_order.client_id', 'ASC')
  844. ->orderBy('supply_order.mailing_address_full', 'ASC')
  845. ->orderBy('supply_order.created_at', 'ASC')
  846. ->select('supply_order.*')
  847. ->paginate();
  848. return view('app.practice-management.supply-orders-ready-to-ship', compact('supplyOrders', 'counts'));
  849. }
  850. public function supplyOrdersShipmentUnderway(Request $request)
  851. {
  852. $counts = $this->getSupplyOrderCounts();
  853. $supplyOrders = SupplyOrder
  854. ::where('is_cancelled', false)
  855. ->whereNotNull('shipment_id')
  856. ->orderBy('client_id', 'ASC')
  857. ->orderBy('mailing_address_full', 'ASC')
  858. ->orderBy('created_at', 'ASC')
  859. ->paginate();
  860. return view('app.practice-management.supply-orders-shipment-underway', compact('supplyOrders', 'counts'));
  861. }
  862. public function supplyOrdersHanging(Request $request)
  863. {
  864. $counts = $this->getSupplyOrderCounts();
  865. $supplyOrders = SupplyOrder
  866. ::select('supply_order.*')
  867. ->leftJoin('shipment', function($join) {
  868. $join->on('supply_order.shipment_id', '=', 'shipment.id');
  869. })
  870. ->where('shipment.status', 'CANCELLED')
  871. ->where('supply_order.is_cancelled', false)
  872. ->orderBy('supply_order.client_id', 'ASC')
  873. ->orderBy('supply_order.mailing_address_full', 'ASC')
  874. ->orderBy('supply_order.created_at', 'ASC')
  875. ->paginate();
  876. return view('app.practice-management.supply-orders-hanging', compact('supplyOrders', 'counts'));
  877. }
  878. public function supplyOrdersCancelledButUnacknowledged(Request $request)
  879. {
  880. $supplyOrders = SupplyOrder::where('signed_by_pro_id', $this->performer()->pro->id)
  881. ->where('is_cancelled', true)
  882. ->where('is_cancellation_acknowledged', false)
  883. ->orderBy('created_at', 'desc')
  884. ->paginate();
  885. return view('app.practice-management.supply-orders-cancelled-but-unacknowledged', compact('supplyOrders'));
  886. }
  887. public function supplyOrdersUnsigned(Request $request)
  888. {
  889. $supplyOrders = SupplyOrder
  890. ::where('is_cancelled', false)
  891. ->where('is_signed_by_pro', false)
  892. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session WHERE pro_id = ?)', [$this->performer()->pro->id])
  893. ->orderBy('created_at', 'desc')
  894. ->paginate();
  895. return view('app.practice-management.supply-orders-unsigned', compact('supplyOrders'));
  896. }
  897. private function getSupplyOrderCounts()
  898. {
  899. return [
  900. "supplyOrders" => SupplyOrder::count(),
  901. "supplyOrdersReadyToShip" => SupplyOrder
  902. ::where('is_cleared_for_shipment', true)
  903. ->where('is_cancelled', false)
  904. ->whereNull('shipment_id')->count(),
  905. "supplyOrdersShipmentUnderway" => SupplyOrder
  906. ::where('is_cancelled', false)
  907. ->whereNotNull('shipment_id')->count(),
  908. "supplyOrdersHanging" => SupplyOrder
  909. ::leftJoin('shipment', function($join) {
  910. $join->on('supply_order.shipment_id', '=', 'shipment.id');
  911. })
  912. ->where('shipment.status', 'CANCELLED')
  913. ->where('supply_order.is_cancelled', false)
  914. ->count(),
  915. ];
  916. }
  917. public function shipmentsReadyToPrint(Request $request)
  918. {
  919. $counts = $this->getShipmentCounts();
  920. $shipments = Shipment
  921. ::where('is_cancelled', false)
  922. ->where('status', 'CREATED')
  923. ->orderBy('created_at', 'ASC')
  924. ->paginate();
  925. return view('app.practice-management.shipments-ready-to-print', compact('shipments', 'counts'));
  926. }
  927. public function shipmentsShipmentUnderway(Request $request)
  928. {
  929. $counts = $this->getShipmentCounts();
  930. $shipments = Shipment
  931. ::where('is_cancelled', false)
  932. ->where('status', 'PRINTED')
  933. ->orderBy('created_at', 'ASC')
  934. ->paginate();
  935. return view('app.practice-management.shipments-waiting-for-picker', compact('shipments', 'counts'));
  936. }
  937. private function getShipmentCounts()
  938. {
  939. return [
  940. "shipments" => Shipment::count(),
  941. "shipmentsReadyToPrint" => Shipment
  942. ::where('is_cancelled', false)
  943. ->where('status', 'CREATED')
  944. ->count(),
  945. "shipmentsWaitingForPicker" => Shipment
  946. ::where('is_cancelled', false)
  947. ->where('status', 'PRINTED')
  948. ->count()
  949. ];
  950. }
  951. public function shipment(Request $request, Shipment $shipment)
  952. {
  953. return view('app.practice-management.shipment', compact('shipment'));
  954. }
  955. public function shipmentsMultiPrint(Request $request, $ids)
  956. {
  957. $ids = array_map(function ($_x) {
  958. return intval($_x);
  959. }, explode("|", $ids));
  960. $shipments = Shipment::whereIn('id', $ids)->get();
  961. return view('app.practice-management.shipments-multi-print', compact('shipments'));
  962. }
  963. public function patientClaimSummary(Request $request, $proUid = null)
  964. {
  965. $notesTotal = DB::select(DB::raw("SELECT COUNT(*) FROM note WHERE is_cancelled IS NOT TRUE"))[0]->count;
  966. $notesTotalWithBillingClosed = DB::select(DB::raw("SELECT COUNT(*) FROM note WHERE is_cancelled IS NOT TRUE AND is_bill_closed IS TRUE"))[0]->count;
  967. $notesTotalWithClaimingClosed = DB::select(DB::raw("SELECT COUNT(*) FROM note WHERE is_cancelled IS NOT TRUE AND is_claim_closed IS TRUE"))[0]->count;
  968. $notes3rdPartyTotal = DB::select(DB::raw("SELECT COUNT(*) FROM note n LEFT JOIN client c ON n.client_id = c.id WHERE n.is_cancelled IS NOT TRUE AND c.is_part_b_primary <> 'YES'"))[0]->count;
  969. $notes3rdPartyTotalWithBillingClosed = DB::select(DB::raw("SELECT COUNT(*) FROM note n LEFT JOIN client c ON n.client_id = c.id WHERE n.is_cancelled IS NOT TRUE AND n.is_bill_closed IS TRUE AND c.is_part_b_primary <> 'YES'"))[0]->count;
  970. $notes3rdPartyTotalWithClaimingClosed = DB::select(DB::raw("SELECT COUNT(*) FROM note n LEFT JOIN client c ON n.client_id = c.id WHERE n.is_cancelled IS NOT TRUE AND n.is_claim_closed IS TRUE AND c.is_part_b_primary <> 'YES'"))[0]->count;
  971. $patientsTotal = DB::select(DB::raw("SELECT COUNT(*) FROM client WHERE is_active IS TRUE AND 0 NOT IN (SELECT c FROM (SELECT COUNT(*) c FROM note WHERE is_cancelled IS NOT TRUE AND note.client_id = client.id) x)"))[0]->count;
  972. $patientsTotalWithBillingClosed = DB::select(DB::raw("SELECT COUNT(*) FROM client WHERE is_active IS TRUE AND 0 NOT IN (SELECT c FROM (SELECT COUNT(*) c FROM note WHERE is_cancelled IS NOT TRUE AND note.client_id = client.id) y) AND 0 IN (SELECT c FROM (SELECT COUNT(*) c FROM note WHERE is_cancelled IS NOT TRUE AND is_bill_closed IS NOT TRUE AND note.client_id = client.id) x)"))[0]->count;
  973. $patientsTotalWithClaimingClosed = DB::select(DB::raw("SELECT COUNT(*) FROM client WHERE is_active IS TRUE AND 0 NOT IN (SELECT c FROM (SELECT COUNT(*) c FROM note WHERE is_cancelled IS NOT TRUE AND note.client_id = client.id) y) AND 0 IN (SELECT c FROM (SELECT COUNT(*) c FROM note WHERE is_cancelled IS NOT TRUE AND is_claim_closed IS NOT TRUE AND note.client_id = client.id) x)"))[0]->count;
  974. $performerPro = $this->performer->pro;
  975. $allPros = [];
  976. if ($performerPro->pro_type == 'ADMIN') {
  977. $allPros = Pro::all();
  978. } else {
  979. $allPros = [$performerPro];
  980. }
  981. //Patient | MCP | # Notes Total | # Notes without Billing Closed | # Notes without Claiming Closed
  982. $patientsQuery = Client::where('is_dummy', '=', false)
  983. ->whereNull('shadow_pro_id')
  984. ->select('id', 'uid', 'name_first', 'name_last', 'mcp_pro_id', 'is_part_b_primary', 'medicare_advantage_plan',
  985. DB::raw("(SELECT name_first||' '||name_last FROM pro where pro.id = client.mcp_pro_id) as mcp"),
  986. DB::raw("(SELECT uid FROM pro where pro.id = mcp_pro_id) as mcp_pro_uid"),
  987. DB::raw("(SELECT COUNT(*) FROM note where note.client_id = client.id) as notes_total"),
  988. DB::raw("(SELECT COUNT(*) FROM note where note.client_id = client.id AND is_bill_closed IS NOT true) as notes_without_billing_closed"),
  989. DB::raw("(SELECT COUNT(*) FROM note where note.client_id = client.id AND is_claim_closed IS NOT true) as notes_without_claiming_closed")
  990. )->orderBy('is_part_b_primary', 'asc')->orderBy('notes_without_claiming_closed', 'desc');
  991. if ($proUid) {
  992. $mcpPro = Pro::where('uid', $proUid)->first();
  993. if ($mcpPro) {
  994. $patientsQuery->where('client.mcp_pro_id', '=', $mcpPro->id);
  995. }
  996. }
  997. $patientsQuery->whereRaw('(SELECT COUNT(*) FROM note where note.client_id = client.id) > 0');
  998. $patientsQuery->orderBy('notes_total', 'DESC');
  999. $patients = $patientsQuery->paginate(50);
  1000. $data = [
  1001. 'patients' => $patients,
  1002. 'proUid' => $proUid,
  1003. 'allPros' => $allPros,
  1004. 'notesTotal' => $notesTotal,
  1005. 'notesTotalWithBillingClosed' => $notesTotalWithBillingClosed,
  1006. 'notesTotalWithClaimingClosed' => $notesTotalWithClaimingClosed,
  1007. 'notes3rdPartyTotal' => $notes3rdPartyTotal,
  1008. 'notes3rdPartyTotalWithBillingClosed' => $notes3rdPartyTotalWithBillingClosed,
  1009. 'notes3rdPartyTotalWithClaimingClosed' => $notes3rdPartyTotalWithClaimingClosed,
  1010. 'patientsTotal' => $patientsTotal,
  1011. 'patientsTotalWithBillingClosed' => $patientsTotalWithBillingClosed,
  1012. 'patientsTotalWithClaimingClosed' => $patientsTotalWithClaimingClosed
  1013. ];
  1014. return view('app.practice-management.patient-claim-summary', $data);
  1015. }
  1016. public function claims(Request $request){
  1017. $status = $request->get('status');
  1018. $claims = [];
  1019. if(!$status){
  1020. $claims = Claim::orderBy('created_at', 'DESC')->paginate();
  1021. }else{
  1022. $claims = Claim::where('status', $status)->orderBy('created_at', 'DESC')->paginate();
  1023. }
  1024. return view('app.practice-management.claims', compact('claims', 'status'));
  1025. }
  1026. public function processClaims(Request $request) {
  1027. $status = '';
  1028. $q = $request->input('q') ? $request->input('q') : '';
  1029. $from = $request->input('from') ? $request->input('from') : '1900-01-01';
  1030. $to = $request->input('to') ? $request->input('to') : '2100-01-01';
  1031. $params = [
  1032. 'q' => '%' . $q . '%',
  1033. 'from' => $from,
  1034. 'to' => $to
  1035. ];
  1036. $hcpPro = $request->input('hcp') ? Pro::where('uid', $request->input('hcp'))->first() : null;
  1037. if($hcpPro) {
  1038. $params['hcp'] = $hcpPro->id;
  1039. }
  1040. $claims = DB::select(DB::raw("
  1041. SELECT claim.uid AS uid,
  1042. DATE(claim.created_at) AS created,
  1043. claim.status,
  1044. client.uid AS client_uid,
  1045. client.cell_number AS client_phone,
  1046. (client.name_last || ' ' || client.name_first) AS client ,
  1047. client.chart_number AS client_chart_number,
  1048. cp.id AS claim_pro_id,
  1049. (cp.name_last || ' ' || cp.name_first) AS claim_pro,
  1050. sp.id AS status_pro_id,
  1051. (sp.name_last || ' ' || sp.name_first) AS status_pro,
  1052. note.uid AS note_uid,
  1053. note.method,
  1054. note.new_or_fu_or_na,
  1055. -- claim.status_updated_at,
  1056. (DATE(claim.status_updated_at) || ' ' ||
  1057. LPAD(EXTRACT(hour FROM claim.status_updated_at)::text, 2, '0') || ':' ||
  1058. LPAD(EXTRACT(minute FROM claim.status_updated_at)::text, 2, '0')) AS status_updated_at,
  1059. (SELECT string_agg(claim_line.cpt, ', ') FROM claim_line where claim_id = claim.id) AS cpts,
  1060. (SELECT COUNT(claim_line_icd.id) FROM claim_line_icd WHERE claim_line_id IN (SELECT id FROM claim_line WHERE claim_id = claim.id)) AS icds,
  1061. ROUND(claim.expected_total, 3) as expected_total
  1062. FROM claim
  1063. join client on claim.client_id = client.id
  1064. join pro cp on claim.pro_id = cp.id
  1065. left join note on claim.note_id = note.id
  1066. left join app_session on claim.status_updated_by_session_id = app_session.id
  1067. left join pro sp on app_session.pro_id = sp.id
  1068. --WHERE claim.status IS NULL OR claim.status = 'NEW'
  1069. WHERE (claim.status is NULL OR claim.status NOT IN ('CANCELLED', 'ABANDONED'))
  1070. -- AND claim.current_version_id IS NOT NULL
  1071. AND (client.name_first ILIKE :q OR
  1072. client.name_last ILIKE :q OR
  1073. client.chart_number ILIKE :q OR
  1074. client.mcn ILIKE :q)
  1075. AND (claim.created_at >= :from AND claim.created_at <= :to)
  1076. " . ($hcpPro ? "AND claim.pro_id = :hcp" : '') . "
  1077. AND claim.id IN (SELECT mb_claim.claim_id FROM mb_claim)
  1078. ORDER BY claim.created_at ASC
  1079. --OFFSET 0 LIMIT 15
  1080. "), $params);
  1081. if($request->input('json')) {
  1082. return json_encode($claims);
  1083. }
  1084. return view('app.practice-management.process-claims', compact('claims', 'status'));
  1085. }
  1086. public function processNotes(Request $request) {
  1087. $mode = $request->input('mode') ? $request->input('mode') : '1';
  1088. if(($mode < 1 || $mode > 5) && $mode != 8) $mode = 1;
  1089. $counts = [
  1090. "picked" => Note::where('is_cancelled', false)
  1091. ->whereNotNull('current_note_pickup_for_processing_id')
  1092. ->count(),
  1093. "bad" => Note::where('is_cancelled', false)
  1094. ->whereRaw("(detail_json)::json->>'isBad' = 'true'")
  1095. ->count(),
  1096. // not yet signed
  1097. "mode-1" => Note::where('is_cancelled', false)
  1098. ->where('is_signed_by_hcp', false)
  1099. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1100. // ->whereNull('current_note_pickup_for_processing_id')
  1101. ->count(),
  1102. // billing not marked done
  1103. "mode-2" => Note::where('is_cancelled', false)
  1104. ->where('is_signed_by_hcp', true)
  1105. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1106. // ->whereNull('current_note_pickup_for_processing_id')
  1107. ->where('is_billing_marked_done', false)
  1108. ->count(),
  1109. // billing not closed
  1110. "mode-3" => Note::where('is_cancelled', false)
  1111. ->where('is_signed_by_hcp', true)
  1112. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1113. // ->whereNull('current_note_pickup_for_processing_id')
  1114. ->where('is_billing_marked_done', true)
  1115. ->where('is_bill_closed', false)
  1116. ->count(),
  1117. // claiming not closed
  1118. "mode-4" => Note::where('is_cancelled', false)
  1119. ->where('is_signed_by_hcp', true)
  1120. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1121. // ->whereNull('current_note_pickup_for_processing_id')
  1122. ->where('is_billing_marked_done', true)
  1123. ->where('is_bill_closed', true)
  1124. ->where('is_claim_closed', false)
  1125. ->count(),
  1126. // has unsubmitted claims
  1127. "mode-5" => Note::where('is_cancelled', false)
  1128. ->where('is_signed_by_hcp', true)
  1129. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1130. // ->whereNull('current_note_pickup_for_processing_id')
  1131. ->where('is_billing_marked_done', true)
  1132. ->where('is_bill_closed', true)
  1133. ->where('is_claim_closed', true)
  1134. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') > 0")
  1135. ->count(),
  1136. // has unsubmitted claims MARKED GOOD!
  1137. "mode-8" => Note::where('is_cancelled', false)
  1138. ->where('is_signed_by_hcp', true)
  1139. ->whereRaw("((detail_json)::json->>'isGood')::text = 'true'")
  1140. // ->whereNull('current_note_pickup_for_processing_id')
  1141. ->where('is_billing_marked_done', true)
  1142. ->where('is_bill_closed', true)
  1143. // ->where('is_claim_closed', true)
  1144. // ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') > 0")
  1145. ->count(),
  1146. // all good
  1147. "mode-6" => Note::where('is_cancelled', false)
  1148. ->where('is_signed_by_hcp', true)
  1149. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1150. // ->whereNull('current_note_pickup_for_processing_id')
  1151. ->where('is_billing_marked_done', true)
  1152. ->where('is_bill_closed', true)
  1153. ->where('is_claim_closed', true)
  1154. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id) > 0")
  1155. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0")
  1156. ->count(),
  1157. "mode-7" => Note::where('is_cancelled', false)
  1158. ->whereRaw("(detail_json)::json->>'isBad' = 'true'")
  1159. ->count(),
  1160. ];
  1161. return view('app.practice-management.process-notes', compact('mode', 'counts'));
  1162. }
  1163. public function getNextNote(Request $request, $mode)
  1164. {
  1165. $note = null;
  1166. switch (+$mode) {
  1167. case 1:
  1168. $note = Note::where('is_cancelled', false)
  1169. ->where('is_signed_by_hcp', false)
  1170. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1171. ->whereNull('current_note_pickup_for_processing_id')
  1172. ->orderBy('effective_dateest', 'DESC')
  1173. ->first();
  1174. break;
  1175. case 2:
  1176. $note = Note::where('is_cancelled', false)
  1177. ->where('is_signed_by_hcp', true)
  1178. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1179. ->whereNull('current_note_pickup_for_processing_id')
  1180. ->where('is_billing_marked_done', false)
  1181. ->orderBy('effective_dateest', 'DESC')
  1182. ->first();
  1183. break;
  1184. case 3:
  1185. $note = Note::where('is_cancelled', false)
  1186. ->where('is_signed_by_hcp', true)
  1187. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1188. ->whereNull('current_note_pickup_for_processing_id')
  1189. ->where('is_billing_marked_done', true)
  1190. ->where('is_bill_closed', false)
  1191. ->orderBy('effective_dateest', 'DESC')
  1192. ->first();
  1193. break;
  1194. case 4:
  1195. $note = Note::where('is_cancelled', false)
  1196. ->where('is_signed_by_hcp', true)
  1197. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1198. ->whereNull('current_note_pickup_for_processing_id')
  1199. ->where('is_billing_marked_done', true)
  1200. ->where('is_bill_closed', true)
  1201. ->where('is_claim_closed', false)
  1202. ->orderBy('effective_dateest', 'DESC')
  1203. ->first();
  1204. break;
  1205. case 5:
  1206. $note = Note::where('is_cancelled', false)
  1207. ->where('is_signed_by_hcp', true)
  1208. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1209. ->whereNull('current_note_pickup_for_processing_id')
  1210. ->where('is_billing_marked_done', true)
  1211. ->where('is_bill_closed', true)
  1212. ->where('is_claim_closed', true)
  1213. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') > 0")
  1214. ->orderBy('effective_dateest', 'DESC')
  1215. ->first();
  1216. break;
  1217. case 8:
  1218. $note = Note::where('is_cancelled', false)
  1219. ->where('is_signed_by_hcp', true)
  1220. ->whereRaw("((detail_json)::json->>'isGood')::text = 'true'")
  1221. // ->whereNull('current_note_pickup_for_processing_id')
  1222. ->where('is_billing_marked_done', true)
  1223. ->where('is_bill_closed', true)
  1224. // ->where('is_claim_closed', true)
  1225. // ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') > 0")
  1226. ->orderBy('effective_dateest', 'DESC')
  1227. ->first();
  1228. break;
  1229. }
  1230. if($note) {
  1231. $note->client_uid = $note->client->uid;
  1232. }
  1233. return json_encode($note);
  1234. }
  1235. public function pickedNotes(Request $request) {
  1236. $counts = [
  1237. "unpicked" => Note::where('is_cancelled', false)
  1238. ->whereNull('current_note_pickup_for_processing_id')
  1239. ->count(),
  1240. ];
  1241. $notes = Note::where('is_cancelled', false)
  1242. ->whereNotNull('current_note_pickup_for_processing_id')
  1243. ->orderBy('effective_dateest', 'ASC')
  1244. ->paginate();
  1245. return view('app.practice-management.picked-notes', compact('counts', 'notes'));
  1246. }
  1247. public function badNotes(Request $request) {
  1248. $counts = [
  1249. "unpicked" => Note::where('is_cancelled', false)
  1250. ->whereNull('current_note_pickup_for_processing_id')
  1251. ->count(),
  1252. ];
  1253. $notes = Note::where('is_cancelled', false)
  1254. ->whereRaw("(detail_json)::json->>'isBad' = 'true'")
  1255. ->orderBy('effective_dateest', 'ASC')
  1256. ->paginate();
  1257. return view('app.practice-management.bad-notes', compact('counts', 'notes'));
  1258. }
  1259. public function doneNotes(Request $request) {
  1260. $counts = [
  1261. "unpicked" => Note::where('is_cancelled', false)
  1262. ->whereNull('current_note_pickup_for_processing_id')
  1263. ->count(),
  1264. ];
  1265. $notes = Note::where('is_cancelled', false)
  1266. ->where('is_signed_by_hcp', true)
  1267. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1268. ->whereNull('current_note_pickup_for_processing_id')
  1269. ->where('is_billing_marked_done', true)
  1270. ->where('is_bill_closed', true)
  1271. ->where('is_claim_closed', true)
  1272. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id) > 0")
  1273. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0")
  1274. ->orderBy('effective_dateest', 'ASC')
  1275. ->paginate();
  1276. return view('app.practice-management.done-notes', compact('counts', 'notes'));
  1277. }
  1278. public function currentMbClaim(Request $request, $claimUid) {
  1279. $claim = Claim::where('uid', $claimUid)->first();
  1280. return json_encode(MBClaim::where('claim_version_id', $claim->currentVersion->id)->first());
  1281. }
  1282. public function currentClaimLines(Request $request, $claimUid) {
  1283. $claim = Claim::where('uid', $claimUid)->first();
  1284. if($request->input('json')) {
  1285. foreach ($claim->lines as $line) {
  1286. $line->expected_total = round($line->expected_total, 3);
  1287. $x = $line->claimLineIcds;
  1288. }
  1289. return json_encode($claim->lines);
  1290. }
  1291. return view('app.practice-management._claim-lines', compact('claim'));
  1292. }
  1293. public function packsMultiPrint(Request $request) {
  1294. $packs = Pack
  1295. ::select('pack.*')
  1296. ->leftJoin('shipment', function($join) {
  1297. $join->on('pack.shipment_id', '=', 'shipment.id');
  1298. })
  1299. ->whereNotIn('shipment.status', ['CANCELLED', 'DISPATCHED'])
  1300. ->where(function ($query) {
  1301. $query->where('pack.status', '<>', 'DELETED')->orWhereNull('pack.status'); // weird, but just the <> isn't working!
  1302. })
  1303. ->whereNotNull('pack.label_system_file_id')
  1304. ->orderBy('pack.created_at', 'ASC')
  1305. ->get();
  1306. return view('app.practice-management.packs-multi-print', compact('packs'));
  1307. }
  1308. public function packsMultiPDF(Request $request, $ids) {
  1309. $ids = array_map(function ($_x) {
  1310. return intval($_x);
  1311. }, explode("|", $ids));
  1312. $packs = Pack::whereIn('id', $ids)->get();
  1313. }
  1314. public function handouts(Request $request) {
  1315. $handouts = Handout::orderBy('display_name')->get();
  1316. return view('app.practice-management.handouts', compact('handouts'));
  1317. }
  1318. private function callJava($request, $endPoint, $data)
  1319. {
  1320. $url = config('stag.backendUrl') . $endPoint;
  1321. $response = Http::asForm()
  1322. ->withHeaders([
  1323. 'sessionKey' => $request->cookie('sessionKey')
  1324. ])
  1325. ->post($url, $data)
  1326. ->body();
  1327. dd($response);
  1328. return $response;
  1329. }
  1330. public function genericBills(Request $request)
  1331. {
  1332. return view('app.practice-management.generic-bills');
  1333. }
  1334. }