PracticeManagementController.php 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993
  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\Company;
  8. use App\Models\Handout;
  9. use App\Models\MBClaim;
  10. use App\Models\Measurement;
  11. use App\Models\Bill;
  12. use App\Models\Claim;
  13. use App\Models\Client;
  14. use App\Models\McpRequest;
  15. use App\Models\McCodeCheck;
  16. use App\Models\Note;
  17. use App\Models\Pack;
  18. use App\Models\Pro;
  19. use App\Models\Product;
  20. use App\Models\ProFavorite;
  21. use App\Models\ProGeneralAvailability;
  22. use App\Models\ProProAccess;
  23. use App\Models\ProRate;
  24. use App\Models\ProSpecificAvailability;
  25. use App\Models\ProSpecificUnavailability;
  26. use App\Models\ProTeam;
  27. use App\Models\ProTextShortcut;
  28. use App\Models\ProTransaction;
  29. use App\Models\Shipment;
  30. use App\Models\SupplyOrder;
  31. use App\Models\Team;
  32. use App\Models\Ticket;
  33. use App\Models\ClientMeasurementDaysPerMonth;
  34. use Illuminate\Support\Facades\DB;
  35. use Illuminate\Support\Facades\Http;
  36. use PDF;
  37. use DateTime;
  38. use DateTimeZone;
  39. use Illuminate\Http\Request;
  40. class PracticeManagementController extends Controller
  41. {
  42. public function mcCodeChecks(Request $request)
  43. {
  44. $checks = McCodeCheck::orderBy('next_eligible_date_professional', 'asc')->get();
  45. return view ('app.practice-management.mc-code-checks', compact('checks'));
  46. }
  47. public function remoteMonitoringReport(Request $request)
  48. {
  49. $rows = null;
  50. $proID = $this->performer()->pro->id;
  51. $isAdmin = $this->performer()->pro->pro_type == 'ADMIN';
  52. //$rows = $isAdmin ? ClientMeasurementDaysPerMonth::all() : ClientMeasurementDaysPerMonth::where('mcp_pro_id', $proID)->orderBy('year_month', 'asc')->orderBy('num_of_days_with_measurement', 'asc')->get();
  53. $rows = CareMonth::whereNotNull('mcp_pro_id')
  54. ->where('number_of_days_with_remote_measurements', '>=', 16)
  55. ->orderByRaw(DB::raw('start_date DESC'))->paginate(50) ;
  56. return view ('app.practice-management.remote-monitoring-report', compact('rows'));
  57. }
  58. public function billingReport(Request $request)
  59. {
  60. $rows = BillingReport::paginate(50);
  61. return view('app.practice-management.billing-report', compact('rows'));
  62. }
  63. public function dashboard(Request $request)
  64. {
  65. return view('app.practice-management.dashboard');
  66. }
  67. public function rates(Request $request, $selectedProUid = 'all')
  68. {
  69. $proUid = $selectedProUid ? $selectedProUid : 'all';
  70. $rates = ProRate::where('is_active', true);
  71. if ($proUid !== 'all') {
  72. $selectedPro = Pro::where('uid', $proUid)->first();
  73. $rates = $rates->where('pro_id', $selectedPro->id);
  74. }
  75. $rates = $rates->orderBy('pro_id', 'asc')->get();
  76. $pros = $this->pros;
  77. return view('app.practice-management.rates', compact('rates', 'pros', 'selectedProUid'));
  78. }
  79. public function previousBills(Request $request)
  80. {
  81. return view('app.practice-management.previous-bills');
  82. }
  83. public function financialTransactions(Request $request)
  84. {
  85. $pro = $this->performer()->pro;
  86. $transactions = null;
  87. if($pro->pro_type === 'ADMIN') {
  88. $transactions = ProTransaction::whereNotNull('id');
  89. }
  90. else {
  91. $transactions = ProTransaction::where('pro_id', $pro->id);
  92. }
  93. $filter = $request->input('p');
  94. if ($filter) {
  95. $filterPro = Pro::where('uid', $filter)->first();
  96. if($filterPro) {
  97. $transactions = $transactions->where('pro_id', '=', $filterPro->id);
  98. }
  99. }
  100. $filter = $request->input('t');
  101. if ($filter) {
  102. $transactions = $transactions->where('plus_or_minus', '=', $filter);
  103. }
  104. $filter = $request->input('c');
  105. if ($filter) {
  106. $transactions = $transactions->where('company_id', '=', $filter);
  107. }
  108. $filter = $request->input('bs');
  109. if ($filter) {
  110. $transactions = $transactions->where('created_at', '>=', $filter);
  111. }
  112. $filter = $request->input('be');
  113. if ($filter) {
  114. $transactions = $transactions->where('created_at', '<=', $filter);
  115. }
  116. $transactions = $transactions->orderBy('created_at', 'desc')->paginate();
  117. $companies = Company::where('is_active', true)->orderBy('name')->get();
  118. return view('app.practice-management.financial-transactions', compact('transactions', 'companies'));
  119. }
  120. public function pendingBillsToSign(Request $request)
  121. {
  122. return view('app.practice-management.pending-bills-to-sign');
  123. }
  124. public function HR(Request $request)
  125. {
  126. return view('app.practice-management.hr');
  127. }
  128. public function directDepositSettings(Request $request)
  129. {
  130. return view('app.practice-management.direct-deposit-settings');
  131. }
  132. public function w9(Request $request)
  133. {
  134. return view('app.practice-management.w9');
  135. }
  136. public function contract(Request $request)
  137. {
  138. return view('app.practice-management.contract');
  139. }
  140. public function notes(Request $request, $filter = '')
  141. {
  142. $proID = $this->performer()->pro->id;
  143. $query = Note::where('hcp_pro_id', $proID);
  144. switch ($filter) {
  145. case 'not-yet-signed':
  146. $query = $query->where('is_signed_by_hcp', false);
  147. break;
  148. case 'not-yet-signed-but-ally-signed':
  149. $query = $query->where('is_signed_by_hcp', false)->where('is_signed_by_ally', true);
  150. break;
  151. case 'without-bills':
  152. $query = $query->where('is_signed_by_hcp', true)->where('is_cancelled', false)->whereDoesntHave('bills');
  153. break;
  154. // more cases can be added as needed
  155. default:
  156. break;
  157. }
  158. $notes = $query->orderBy('created_at', 'desc')->get();
  159. return view('app.practice-management.notes', compact('notes', 'filter'));
  160. }
  161. public function dnaNotesPendingMcpSign(Request $request)
  162. {
  163. $proID = $this->performer()->pro->id;
  164. $notes = Note::where('ally_pro_id', $proID)
  165. ->where('is_signed_by_hcp', false)
  166. ->where('is_cancelled', false)
  167. ->orderBy('created_at', 'desc')
  168. ->get();
  169. return view('app.practice-management.dna-notes-pending-mcp-sign', compact('notes'));
  170. }
  171. public function naBillableSignedNotes(Request $request)
  172. {
  173. $notes = Note
  174. ::where('is_signed_by_hcp', TRUE)
  175. ->where('ally_pro_id', $this->performer()->pro->id)
  176. ->where('is_cancelled', FALSE)
  177. ->whereRaw("
  178. (
  179. SELECT count(bill.id)
  180. FROM bill WHERE
  181. bill.is_cancelled = FALSE AND
  182. bill.generic_pro_id = {$this->performer()->pro->id} AND
  183. bill.note_id = note.id
  184. ) = 0
  185. ");
  186. $notes = $notes->orderBy('created_at', 'desc')->get();
  187. return view('app.practice-management.na-billable-signed-notes', compact('notes'));
  188. }
  189. public function bills(Request $request, $filter = '')
  190. {
  191. $proID = $this->performer()->pro->id;
  192. $query = Bill::where('is_cancelled', false)->where('bill_service_type', '<>', 'CARE_MONTH');
  193. switch ($filter) {
  194. case 'not-yet-signed':
  195. $query = $query
  196. ->where(function ($q) use ($proID) {
  197. $q->where(function ($q2) use ($proID) {
  198. $q2->where('hcp_pro_id', $proID)->where('is_signed_by_hcp', false);
  199. })
  200. ->orWhere(function ($q2) use ($proID) {
  201. $q2->where('cm_pro_id', $proID)->where('is_signed_by_cm', false);
  202. })
  203. ->orWhere(function ($q2) use ($proID) {
  204. $q2->where('rme_pro_id', $proID)->where('is_signed_by_rme', false);
  205. })
  206. ->orWhere(function ($q2) use ($proID) {
  207. $q2->where('rmm_pro_id', $proID)->where('is_signed_by_rmm', false);
  208. });
  209. });
  210. break;
  211. case 'previous':
  212. $query = $query
  213. ->where(function ($q) use ($proID) {
  214. $q->where(function ($q2) use ($proID) {
  215. $q2->where('hcp_pro_id', $proID)->where('is_signed_by_hcp', true);
  216. })
  217. ->orWhere(function ($q2) use ($proID) {
  218. $q2->where('cm_pro_id', $proID)->where('is_signed_by_cm', true);
  219. })
  220. ->orWhere(function ($q2) use ($proID) {
  221. $q2->where('rme_pro_id', $proID)->where('is_signed_by_rme', true);
  222. })
  223. ->orWhere(function ($q2) use ($proID) {
  224. $q2->where('rmm_pro_id', $proID)->where('is_signed_by_rmm', true);
  225. });
  226. });
  227. break;
  228. // more cases can be added as needed
  229. default:
  230. $query = $query
  231. ->where(function ($q) use ($proID) {
  232. $q->where(function ($q2) use ($proID) {
  233. $q2->where('hcp_pro_id', $proID);
  234. })
  235. ->orWhere(function ($q2) use ($proID) {
  236. $q2->where('cm_pro_id', $proID);
  237. })
  238. ->orWhere(function ($q2) use ($proID) {
  239. $q2->where('rme_pro_id', $proID);
  240. })
  241. ->orWhere(function ($q2) use ($proID) {
  242. $q2->where('rmm_pro_id', $proID);
  243. });
  244. });
  245. break;
  246. }
  247. $bills = $query->orderBy('created_at', 'desc')->get();
  248. return view('app.practice-management.bills', compact('bills', 'filter'));
  249. }
  250. public function rmBillsToSign(Request $request)
  251. {
  252. $performerProID = $this->performer()->pro->id;
  253. $bills = Bill::where('is_cancelled', false)->where('cm_or_rm', 'RM')
  254. ->where(function ($q) use ($performerProID) {
  255. $q
  256. ->where(function ($q2) use ($performerProID) {
  257. $q2->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false);
  258. })
  259. ->orWhere(function ($q2) use ($performerProID) {
  260. $q2->where('rme_pro_id', $performerProID)->where('is_signed_by_rme', false);
  261. })
  262. ->orWhere(function ($q2) use ($performerProID) {
  263. $q2->where('rmm_pro_id', $performerProID)->where('is_signed_by_rmm', false);
  264. })
  265. ->orWhere(function ($q2) use ($performerProID) {
  266. $q2->where('generic_pro_id', $performerProID)->where('is_signed_by_generic_pro', false);
  267. });
  268. })
  269. ->orderBy('effective_date', 'desc')
  270. ->get();
  271. return view('app.practice-management.rm-bills-to-sign', compact('bills'));
  272. }
  273. public function unacknowledgedCancelledBills(Request $request)
  274. {
  275. $bills = Bill::where('hcp_pro_id', $this->performer()->pro->id)
  276. ->where('is_cancelled', true)
  277. ->where('is_cancellation_acknowledged', false)
  278. ->orderBy('created_at', 'desc')
  279. ->get();
  280. return view('app.practice-management.unacknowledged-cancelled-bills', compact('bills'));
  281. }
  282. public function myTickets(Request $request, $filter = 'open')
  283. {
  284. $performer = $this->performer();
  285. $myTickets = Ticket::where(function ($q) use ($performer) {
  286. $q->where('assigned_pro_id', $performer->pro_id)
  287. ->orWhere('manager_pro_id', $performer->pro_id)
  288. ->orWhere('ordering_pro_id', $performer->pro_id)
  289. ->orWhere('initiating_pro_id', $performer->pro_id);
  290. });
  291. if ($filter === 'open') {
  292. $myTickets = $myTickets->where('is_open', true);
  293. } else if ($filter === 'closed') {
  294. $myTickets = $myTickets->where('is_open', false);
  295. }
  296. $myTickets = $myTickets->orderBy('created_at', 'desc')->get();
  297. return view('app.practice-management.my-tickets', compact('myTickets', 'filter'));
  298. }
  299. public function myTextShortcuts(Request $request)
  300. {
  301. $myTextShortcuts = DB::table('pro_text_shortcut')
  302. ->leftJoin('pro', 'pro_text_shortcut.pro_id', '=', 'pro.id')
  303. ->select(
  304. 'pro_text_shortcut.uid',
  305. 'pro_text_shortcut.shortcut',
  306. 'pro_text_shortcut.text',
  307. 'pro.name_first',
  308. 'pro.name_last'
  309. )
  310. ->where('pro_text_shortcut.is_removed', false);
  311. if($this->performer()->pro->pro_type !== 'ADMIN') {
  312. $myTextShortcuts = $myTextShortcuts->where('pro_id', $this->performer()->pro_id);
  313. }
  314. $myTextShortcuts = $myTextShortcuts
  315. ->orderBy('pro.name_last')
  316. ->orderBy('pro.name_first')
  317. ->get();
  318. return view('app.practice-management.my-text-shortcuts', compact('myTextShortcuts'));
  319. }
  320. public function myFavorites(Request $request, $filter = 'all')
  321. {
  322. $performer = $this->performer();
  323. $myFavorites = ProFavorite::where('pro_id', $performer->pro_id)
  324. ->where('is_removed', false);
  325. if ($filter !== 'all') {
  326. $myFavorites = $myFavorites->where('category', $filter);
  327. }
  328. $myFavorites = $myFavorites
  329. ->orderBy('category', 'asc')
  330. ->orderBy('position_index', 'asc')
  331. ->get();
  332. return view('app.practice-management.my-favorites', compact('myFavorites', 'filter'));
  333. }
  334. public function patientsWithoutCoverage(Request $request, $filter = 'all')
  335. {
  336. $performer = $this->performer();
  337. $sql = "SELECT cl.uid, cl.name_first, cl.name_last FROM client cl ";
  338. $joinClause = 'LEFT JOIN client_primary_coverage cpc ON cl.latest_client_primary_coverage_id = cpc.id ';
  339. $withoutCondition = "cl.latest_client_primary_coverage_id IS NULL";
  340. $pendingCondition = "
  341. (cl.latest_client_primary_coverage_id IS NOT NULL -- coverage exists, but status is null or unknown
  342. AND (
  343. (cpc.plan_type = 'MEDICARE' AND (cpc.is_partbprimary = 'UNKNOWN' OR cpc.is_partbprimary IS NULL))
  344. OR
  345. (cpc.plan_type != 'MEDICARE' AND
  346. (cpc.manual_determination_category = 'UNKNOWN' OR cpc.manual_determination_category IS NULL))
  347. ))";
  348. switch ($filter) {
  349. case 'without-coverage-information':
  350. $sql .= 'WHERE cl.shadow_pro_id IS NULL AND ';
  351. $sql .= $withoutCondition;
  352. break;
  353. case 'pending-coverage-verification':
  354. $sql .= $joinClause . 'WHERE cl.shadow_pro_id IS NULL AND ';
  355. $sql .= $pendingCondition;
  356. break;
  357. default:
  358. $sql .= $joinClause . 'WHERE cl.shadow_pro_id IS NULL AND ';
  359. $sql .= '(' . $withoutCondition . ' OR ' . $pendingCondition . ')';
  360. break;
  361. }
  362. $sql .= ' ORDER BY cl.name_first ASC';
  363. $pendingCoverage = DB::select(DB::raw($sql));
  364. return view('app.practice-management.patients-without-coverage', compact('pendingCoverage', 'filter'));
  365. }
  366. public function proAvailability(Request $request, $proUid = null)
  367. {
  368. $performer = $this->performer();
  369. $pro = $performer->pro;
  370. if ($proUid) {
  371. $pro = Pro::where('uid', $proUid)->first();
  372. }
  373. if ($request->get('pro_uid')) {
  374. $proUid = $request->get('pro_uid');
  375. $pro = Pro::where('uid', $proUid)->first();
  376. }
  377. $selectedProUid = $pro->uid;
  378. $pros = $this->pros;
  379. $generalAvailabilitiesList = ProGeneralAvailability::where('pro_id', $pro->id)->where('is_cancelled', false)->orderBy('created_at', 'asc')->get();
  380. $generalAvailabilities = [
  381. 'MONDAY' => [],
  382. 'TUESDAY' => [],
  383. 'WEDNESDAY' => [],
  384. 'THURSDAY' => [],
  385. 'FRIDAY' => [],
  386. 'SATURDAY' => [],
  387. 'SUNDAY' => [],
  388. ];
  389. foreach ($generalAvailabilitiesList as $ga) {
  390. if ($ga->day_of_week == 'MONDAY') {
  391. $generalAvailabilities['MONDAY'][] = $ga;
  392. }
  393. if ($ga->day_of_week == 'TUESDAY') {
  394. $generalAvailabilities['TUESDAY'][] = $ga;
  395. }
  396. if ($ga->day_of_week == 'WEDNESDAY') {
  397. $generalAvailabilities['WEDNESDAY'][] = $ga;
  398. }
  399. if ($ga->day_of_week == 'THURSDAY') {
  400. $generalAvailabilities['THURSDAY'][] = $ga;
  401. }
  402. if ($ga->day_of_week == 'FRIDAY') {
  403. $generalAvailabilities['FRIDAY'][] = $ga;
  404. }
  405. if ($ga->day_of_week == 'SATURDAY') {
  406. $generalAvailabilities['SATURDAY'][] = $ga;
  407. }
  408. if ($ga->day_of_week == 'SUNDAY') {
  409. $generalAvailabilities['SUNDAY'][] = $ga;
  410. }
  411. }
  412. $specificAvailabilities = ProSpecificAvailability::where('pro_id', $pro->id)->where('is_cancelled', false)->orderBy('start_time')->get();
  413. $specificUnavailabilities = ProSpecificUnavailability::where('pro_id', $pro->id)->where('is_cancelled', false)->orderBy('start_time', 'asc')->get();
  414. //events for the calendar
  415. $startDate = date('Y-m-d', strtotime("sunday -1 week"));
  416. $endDateTime = new DateTime($startDate);
  417. $endDateTime->modify('+6 day');
  418. $endDate = $endDateTime->format("Y-m-d");
  419. $eventsData = $pro->getAvailabilityEvents($startDate, $endDate);
  420. $events = json_encode($eventsData);
  421. return view(
  422. 'app.practice-management.pro-availability',
  423. compact(
  424. 'pros',
  425. 'generalAvailabilities',
  426. 'specificAvailabilities',
  427. 'specificUnavailabilities',
  428. 'events',
  429. 'selectedProUid'
  430. )
  431. );
  432. }
  433. public function loadAvailability(Request $request, $proUid)
  434. {
  435. $performer = $this->performer();
  436. $pro = $performer->pro;
  437. $startDate = $request->get('start');
  438. $endDate = $request->get('end');
  439. $selectedPro = Pro::where('uid', $proUid)->first();
  440. return $selectedPro->getAvailabilityEvents($startDate, $endDate, $request->input('tz') ? $request->input('tz') : 'EASTERN');
  441. }
  442. public function proAvailabilityFilter(Request $request)
  443. {
  444. $proUid = $request->get('proUid');
  445. return ['success' => true, 'data' => $proUid];
  446. }
  447. // video call page (RHS)
  448. // generic call handle (no uid)
  449. // specific call handle (uid of client)
  450. public function meet(Request $request, $uid = false)
  451. {
  452. $session = AppSession::where('session_key', $request->cookie('sessionKey'))->first();
  453. $client = !empty($uid) ? Client::where('uid', $uid)->first() : null;
  454. if (!empty($client)) {
  455. return view('app.video.call-minimal', compact('session', 'client'));
  456. }
  457. return view('app.video.call-agora-v2', compact('session', 'client'));
  458. }
  459. // check video page
  460. public function checkVideo(Request $request, $uid)
  461. {
  462. $session = AppSession::where('session_key', $request->cookie('sessionKey'))->first();
  463. $client = !empty($uid) ? Client::where('uid', $uid)->first() : null;
  464. $publish = false;
  465. return view('app.video.check-video-minimal', compact('session', 'client'));
  466. }
  467. public function getParticipantInfo(Request $request)
  468. {
  469. $sid = intval($request->get('uid')) - 1000000;
  470. $session = AppSession::where('id', $sid)->first();
  471. $result = [
  472. "type" => '',
  473. "name" => ''
  474. ];
  475. if ($session) {
  476. $result["type"] = $session->session_type;
  477. switch ($session->session_type) {
  478. case 'PRO':
  479. $pro = Pro::where('id', $session->pro_id)->first();
  480. $result["name"] = $pro->displayName();
  481. break;
  482. case 'CLIENT':
  483. $client = Client::where('id', $session->client_id)->first();
  484. $result["name"] = $client->displayName();
  485. break;
  486. }
  487. }
  488. return json_encode($result);
  489. }
  490. // ajax ep used by the video page
  491. // this is needed bcoz meet() is used not
  492. // just for the client passed to the view
  493. public function getOpentokSessionKey(Request $request, $uid)
  494. {
  495. $client = Client::where('uid', $uid)->first();
  496. return json_encode(["data" => $client ? $client->opentok_session_id : '']);
  497. }
  498. // poll to check if there are patients with active mcp requests
  499. public function getPatientsInQueue(Request $request)
  500. {
  501. $myInitiatives = $this->performer->pro->initiatives;
  502. if ($myInitiatives) {
  503. $myInitiatives = strtoupper($myInitiatives);
  504. }
  505. $myInitiativesList = explode('|', $myInitiatives);
  506. $myForeignLanguages = $this->performer->pro->foreign_languages;
  507. if ($myForeignLanguages) {
  508. $myForeignLanguages = strtoupper($myForeignLanguages);
  509. }
  510. $myForeignLanguagesList = explode('|', $myForeignLanguages);
  511. $clients = Client::whereNotNull('active_mcp_request_id')->where(function ($query) use ($myInitiativesList) {
  512. $query->whereNull('initiative')->orWhereIn('initiative', $myInitiativesList);
  513. })
  514. ->where(function ($query) use ($myForeignLanguagesList) {
  515. $query->whereNull('preferred_foreign_language')->orWhereIn('preferred_foreign_language', $myForeignLanguagesList);
  516. })->limit(3)->get();
  517. $results = [];
  518. foreach ($clients as $client) {
  519. $results[] = [
  520. 'clientUid' => $client->uid,
  521. 'name' => $client->displayName(),
  522. 'initials' => substr($client->name_first, 0, 1) . substr($client->name_last, 0, 1)
  523. ];
  524. }
  525. return json_encode($results);
  526. }
  527. public function currentWork(Request $request)
  528. {
  529. return view('app/current-work');
  530. }
  531. public function calendar(Request $request, $proUid = null)
  532. {
  533. $pros = Pro::all();
  534. if ($this->pro && $this->pro->pro_type != 'ADMIN') {
  535. $accessiblePros = ProProAccess::where('owner_pro_id', $this->pro->id);
  536. $accessibleProIds = [];
  537. foreach ($accessiblePros as $accessiblePro) {
  538. $accessibleProIds[] = $accessiblePro->id;
  539. }
  540. $accessibleProIds[] = $this->pro->id;
  541. $pros = Pro::whereIn('id', $accessibleProIds)->get();
  542. }
  543. return view('app.practice-management.calendar', compact('pros'));
  544. }
  545. public function cellularDeviceManager(Request $request, $proUid = null)
  546. {
  547. $proUid = $proUid ? $proUid : $request->get('pro-uid');
  548. $performerPro = $this->performer->pro;
  549. $targetPro = null;
  550. $expectedForHcp = null;
  551. if ($performerPro->pro_type == 'ADMIN') {
  552. $targetPro = Pro::where('uid', $proUid)->first();
  553. } else {
  554. $targetPro = $performerPro;
  555. }
  556. $clients = [];
  557. if ($targetPro) {
  558. $clients = Client::where('mcp_pro_id', $targetPro->id)->orderBy('created_at', 'desc')->paginate(20);
  559. } else {
  560. $clients = Client::orderBy('created_at', 'desc')->paginate(20);
  561. }
  562. return view('app.practice-management.cellular-device-manager', compact('clients', 'targetPro', 'proUid'));
  563. }
  564. public function treatmentServiceUtil(Request $request)
  565. {
  566. $view_treatment_service_utilization_org = DB::select(DB::raw("SELECT * FROM view_treatment_service_utilization_org ORDER BY effective_date DESC"));
  567. $view_treatment_service_utilization = DB::select(DB::raw("SELECT * FROM view_treatment_service_utilization ORDER BY effective_date DESC, total_hrs DESC"));
  568. $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"));
  569. return view('app.practice-management.treatment-services-util', compact(
  570. 'view_treatment_service_utilization_org',
  571. 'view_treatment_service_utilization',
  572. 'view_treatment_service_utilization_by_patient'));
  573. }
  574. public function processingBillMatrix(Request $request, $proUid = null)
  575. {
  576. $proUid = $proUid ? $proUid : $request->get('pro-uid');
  577. $performerPro = $this->performer->pro;
  578. $targetPro = null;
  579. if ($performerPro->pro_type == 'ADMIN') {
  580. $targetPro = Pro::where('uid', $proUid)->first();
  581. } else {
  582. $targetPro = $performerPro;
  583. }
  584. $bills = Bill::where('is_cancelled', false);
  585. if(!$request->input('t') || $request->input('t') === 'hcp') {
  586. $bills = $bills
  587. ->where('has_hcp_been_paid', false)
  588. ->where('is_signed_by_hcp', true);
  589. if ($targetPro) {
  590. $bills = $bills->where('hcp_pro_id', $targetPro->id);
  591. }
  592. if($request->input('c')) {
  593. $bills = $bills->whereRaw('(SELECT company_id from company_pro where id = hcp_company_pro_id) = ' . $request->input('c'));
  594. }
  595. }
  596. else if($request->input('t') === 'na') {
  597. $bills = $bills
  598. ->where('has_generic_pro_been_paid', false)
  599. ->where('is_signed_by_generic_pro', true);
  600. if ($targetPro) {
  601. $bills = $bills->where('generic_pro_id', $targetPro->id);
  602. }
  603. if($request->input('c')) {
  604. $bills = $bills->whereRaw('(SELECT company_id from company_pro where id = generic_company_pro_id) = ' . $request->input('c'));
  605. }
  606. }
  607. $filter = $request->input('f');
  608. switch ($filter) {
  609. case 'verified':
  610. $bills = $bills->where('is_verified', true);
  611. break;
  612. case 'not-verified':
  613. $bills = $bills->where('is_verified', false);
  614. break;
  615. }
  616. $filter = $request->input('bs');
  617. if ($filter) {
  618. $bills = $bills->where('balance_post_date', '>=', $filter);
  619. }
  620. $filter = $request->input('be');
  621. if ($filter) {
  622. $bills = $bills->where('balance_post_date', '<=', $filter);
  623. }
  624. $filter = $request->input('s');
  625. if ($filter) {
  626. $bills = $bills->where('code', '=', $filter);
  627. }
  628. $bills = $bills->orderBy('effective_date', 'desc')->paginate();
  629. $companies = Company::where('is_active', true)->orderBy('name')->get();
  630. $codes = DB::select(DB::raw("SELECT code, count(*) as count FROM bill WHERE is_cancelled IS FALSE GROUP BY code ORDER BY code"));
  631. $viewData = [
  632. 'bills' => $bills,
  633. 'targetPro' => $targetPro,
  634. 'performerPro' => $performerPro,
  635. 'proUid' => $proUid,
  636. 'companies' => $companies,
  637. 'codes' => $codes
  638. ];
  639. return view('app.practice-management.processing-bill-matrix', $viewData);
  640. }
  641. public function proFinancials(Request $request, $proUid = null)
  642. {
  643. $proUid = $proUid ? $proUid : $request->get('pro-uid');
  644. $performerPro = $this->performer->pro;
  645. $targetPro = null;
  646. if ($performerPro->pro_type == 'ADMIN') {
  647. $targetPro = Pro::where('uid', $proUid)->first();
  648. } else {
  649. $targetPro = $performerPro;
  650. }
  651. $fPros = Pro::whereNotNull('balance');
  652. if($targetPro) {
  653. $fPros = $fPros->where('uid', $targetPro->uid);
  654. }
  655. $fPros = $fPros
  656. ->where('balance', '>', 0)
  657. ->orderBy('name_last')
  658. ->orderBy('name_first')
  659. ->paginate();
  660. return view('app.practice-management.pro-financials', compact('fPros', 'targetPro'));
  661. }
  662. public function hcpBillMatrix(Request $request, $proUid = null)
  663. {
  664. $proUid = $proUid ? $proUid : $request->get('pro-uid');
  665. $performerPro = $this->performer->pro;
  666. $targetPro = null;
  667. $allPros = [];
  668. $expectedForHcp = null;
  669. if ($performerPro->pro_type == 'ADMIN') {
  670. $allPros = Pro::all();
  671. $targetPro = Pro::where('uid', $proUid)->first();
  672. } else {
  673. $targetPro = $performerPro;
  674. }
  675. $rows = [];
  676. if ($targetPro) {
  677. $rows = DB::select(DB::raw("SELECT * FROM aemish_bill_report WHERE hcp_pro_id = :targetProID"), ['targetProID' => $targetPro->id]);
  678. } else {
  679. $rows = DB::select(DB::raw("SELECT * FROM aemish_bill_report"));
  680. }
  681. return view('app.practice-management.hcp-bill-matrix', compact('rows', 'allPros', 'expectedForHcp', 'targetPro', 'proUid'));
  682. }
  683. public function billingManager(Request $request, $proUid = null)
  684. {
  685. $proUid = $proUid ? $proUid : $request->get('pro-uid');
  686. $performerPro = $this->performer->pro;
  687. $targetPro = null;
  688. $allPros = [];
  689. $expectedForHcp = null;
  690. if ($performerPro->pro_type == 'ADMIN') {
  691. $allPros = Pro::all();
  692. $targetPro = Pro::where('uid', $proUid)->first();
  693. } else {
  694. $targetPro = $performerPro;
  695. }
  696. $notes = [];
  697. if ($targetPro) {
  698. $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;
  699. $notes = Note::where('hcp_pro_id', $targetPro->id);
  700. } else {
  701. $notes = Note::where('id', '>', 0);
  702. }
  703. if($request->input('date')) {
  704. $notes = $notes->where('effective_dateest', $request->input('date'));
  705. }
  706. $filters = [];
  707. $filters['bills_created'] = $request->input('bills_created');
  708. $filters['is_billing_marked_done'] = $request->input('is_billing_marked_done');
  709. $filters['bills_resolved'] = $request->input('bills_resolved');
  710. $filters['bills_closed'] = $request->input('bills_closed');
  711. $filters['claims_created'] = $request->input('claims_created');
  712. $filters['claims_closed'] = $request->input('claims_closed');
  713. if ($filters['bills_created']) {
  714. $notes->where(
  715. 'bill_total_expected',
  716. ($filters['bills_created'] === 'yes' ? '>' : '<='),
  717. 0);
  718. }
  719. if ($filters['is_billing_marked_done']) {
  720. $notes->where(
  721. 'is_billing_marked_done',
  722. ($filters['is_billing_marked_done'] === 'yes' ? '=' : '!='),
  723. true);
  724. }
  725. if ($filters['bills_resolved']) {
  726. $notes->whereRaw('(SELECT count(id) FROM bill WHERE note_id = note.id) > 0'); // have bills
  727. if ($filters['bills_resolved'] === 'yes') {
  728. $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');
  729. } elseif ($filters['bills_resolved'] === 'no') {
  730. $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');
  731. }
  732. }
  733. if ($filters['bills_closed']) {
  734. $notes->where(
  735. 'is_bill_closed',
  736. ($filters['bills_closed'] === 'yes' ? '=' : '!='),
  737. true);
  738. }
  739. if ($filters['claims_created']) {
  740. $notes->where(
  741. 'claim_total_expected',
  742. ($filters['claims_created'] === 'yes' ? '>' : '<='),
  743. 0);
  744. }
  745. if ($filters['claims_closed']) {
  746. $notes->where(
  747. 'is_claim_closed',
  748. ($filters['claims_closed'] === 'yes' ? '=' : '!='),
  749. true);
  750. }
  751. $notes = $notes->orderBy('effective_dateest', 'desc')->paginate(20);
  752. return view('app.practice-management.billing-manager', compact('notes', 'allPros', 'expectedForHcp', 'targetPro', 'proUid', 'filters'));
  753. }
  754. public function remoteMonitoring(Request $request) {
  755. $performer = $this->performer();
  756. $ym = ($request->input('y') ?: 'Y') . '-' . ($request->input('m') ?: 'm');
  757. $careMonthStart = date($ym . '-01');
  758. // filters
  759. $filters = '';
  760. $fmd = $request->input('fmd');
  761. if($fmd && $fmd !== 'all') {
  762. switch($fmd) {
  763. case 'lt16':
  764. $filters .= ' AND (care_month.number_of_days_with_remote_measurements < 16 OR care_month.number_of_days_with_remote_measurements IS NULL) ';
  765. break;
  766. case 'gte16':
  767. $filters .= ' AND (care_month.number_of_days_with_remote_measurements >= 16 AND care_month.number_of_days_with_remote_measurements IS NOT NULL) ';
  768. break;
  769. }
  770. }
  771. $fcomm = $request->input('fcomm');
  772. if($fcomm && $fcomm !== 'all') {
  773. switch($fcomm) {
  774. case 'not-done':
  775. $filters .= ' 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) ';
  776. break;
  777. case 'done':
  778. $filters .= ' 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) ';
  779. break;
  780. }
  781. }
  782. $c = $request->input('c');
  783. if($c) {
  784. $filters .= ' AND client.uid = \'' . $request->input('c') . '\' ';
  785. }
  786. $patients = DB::select(
  787. DB::raw(
  788. "
  789. SELECT client.name_first, client.name_last, client.uid as client_uid,
  790. care_month.uid as care_month_uid,
  791. care_month.id as care_month_id,
  792. care_month.start_date,
  793. care_month.number_of_days_with_remote_measurements,
  794. care_month.has_anyone_interacted_with_client_about_rm_outside_note,
  795. care_month.rm_num_measurements_not_stamped_by_mcp,
  796. care_month.rm_num_measurements_not_stamped_by_non_hcp,
  797. care_month.rm_num_measurements_not_stamped_by_rmm,
  798. care_month.rm_num_measurements_not_stamped_by_rme,
  799. client.mcp_pro_id,
  800. client.default_na_pro_id,
  801. client.rmm_pro_id,
  802. client.rme_pro_id,
  803. client.cell_number
  804. FROM care_month join client on care_month.client_id = client.id
  805. WHERE
  806. EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  807. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  808. {$filters}
  809. ORDER BY care_month.number_of_days_with_remote_measurements DESC NULLS LAST, client.name_first ASC, client.name_last ASC
  810. "
  811. )
  812. );
  813. $timestamp = strtotime(date('Y-m-d'));
  814. $daysRemaining = (int)date('t', $timestamp) - (int)date('j', $timestamp);
  815. return view('app.practice-management.remote-monitoring', compact('patients', 'daysRemaining', 'careMonthStart'));
  816. }
  817. public function remoteMonitoringMeasurements(Request $request, CareMonth $careMonth) {
  818. $performer = $this->performer();
  819. $measurements = DB::select(
  820. DB::raw(
  821. "
  822. SELECT measurement.label,
  823. measurement.ts,
  824. measurement.effective_date,
  825. measurement.sbp_mm_hg,
  826. measurement.dbp_mm_hg,
  827. measurement.value_pulse,
  828. measurement.value_irregular,
  829. measurement.numeric_value,
  830. measurement.value,
  831. measurement.uid,
  832. client.name_first,
  833. client.name_last,
  834. client.mcp_pro_id,
  835. client.default_na_pro_id,
  836. client.rmm_pro_id,
  837. client.rme_pro_id
  838. FROM measurement RIGHT JOIN client on measurement.client_id = client.id
  839. WHERE
  840. client.id = {$careMonth->client_id}
  841. AND measurement.label IS NOT NULL
  842. AND measurement.label NOT IN ('SBP', 'DBP')
  843. AND (measurement.is_cellular_zero = FALSE or measurement.is_cellular_zero IS NULL)
  844. AND measurement.is_removed IS FALSE
  845. AND measurement.client_bdt_measurement_id IS NOT NULL
  846. AND measurement.care_month_id = {$careMonth->id}
  847. AND (
  848. (client.mcp_pro_id = {$performer->pro->id} AND measurement.has_been_stamped_by_mcp IS FALSE)
  849. OR (client.rmm_pro_id = {$performer->pro->id} AND measurement.has_been_stamped_by_rmm IS FALSE)
  850. OR (client.rme_pro_id = {$performer->pro->id} AND measurement.has_been_stamped_by_rme IS FALSE)
  851. OR (client.default_na_pro_id = {$performer->pro->id} AND measurement.has_been_stamped_by_non_hcp IS FALSE)
  852. )
  853. ORDER BY ts DESC
  854. "
  855. )
  856. );
  857. return view('app.practice-management.remote-monitoring-measurements', compact('careMonth', 'measurements'));
  858. }
  859. public function billMatrix(Request $request)
  860. {
  861. $bClients = [];
  862. $bHCPPros = [];
  863. $bNAPros = [];
  864. $filters = [];
  865. $filters['client'] = $request->input('client');
  866. $filters['service'] = $request->input('service');
  867. $filters['hcp'] = $request->input('hcp');
  868. $filters['hcp_paid'] = $request->input('hcp_paid');
  869. $filters['expected_op'] = $request->input('expected_op');
  870. $filters['expected_value'] = $request->input('expected_value');
  871. $filters['paid_op'] = $request->input('paid_op');
  872. $filters['paid_value'] = $request->input('paid_value');
  873. $filters['bal_post_date_op'] = $request->input('bal_post_date_op');
  874. $filters['bal_post_date_value'] = $request->input('bal_post_date_value');
  875. $filters['hcp_sign'] = $request->input('hcp_sign');
  876. $filters['verified'] = $request->input('verified');
  877. $filters['cancelled'] = $request->input('cancelled');
  878. $bills = Bill::orderBy('effective_date')->paginate();
  879. return view('app.practice-management.bill-matrix', compact('bills', 'bClients', 'bHCPPros', 'filters'));
  880. }
  881. public function medicarePartBClaims(Request $request)
  882. {
  883. $medicarePartBOnly = $request->get("medicare_part_b");
  884. $allClaims = Claim::where('was_submitted', false)->orWhere('was_submitted', null)->orderBy('created_at', 'desc')->get();
  885. //Only medicare claims
  886. $claims = [];
  887. foreach ($allClaims as $claim) {
  888. if ($claim->client != null && $claim->client->getPrimaryCoverageStatus() == 'YES' && !$claim->edi) {
  889. $claims[] = $claim;
  890. }
  891. }
  892. $claimEDIs = ClaimEDI::all();
  893. return view('app.practice-management.medicare-partb-claims', compact('claims', 'claimEDIs'));
  894. }
  895. // Generate PDF
  896. public function downloadClaims()
  897. {
  898. $claims = Claim::where('was_submitted', false)->orWhere('was_submitted', null)->orderBy('created_at', 'desc')->limit(100)->get();
  899. view()->share('claims', $claims);
  900. $pdf = PDF::loadView('app.practice-management.claims-pdf', $claims);
  901. return $pdf->download('pdf_file.pdf');
  902. }
  903. public function tickets(Request $request, $proUid = null)
  904. {
  905. $tickets = Ticket::orderBy('created_at', 'desc')->paginate();
  906. return view('app.practice-management.tickets', compact('tickets'));
  907. }
  908. public function supplyOrders(Request $request)
  909. {
  910. // counts
  911. $counts = $this->getSupplyOrderCounts();
  912. // so clients
  913. $soClientIDs = DB::table('supply_order')->select('client_id')->distinct()->get()->toArray();
  914. $soClientIDs = array_map(function ($_x) {
  915. return $_x->client_id;
  916. }, $soClientIDs);
  917. $soClients = Client::whereIn('id', $soClientIDs)->get();
  918. // so products
  919. $soProductIDs = DB::table('supply_order')->select('product_id')->distinct()->get()->toArray();
  920. $soProductIDs = array_map(function ($_x) {
  921. return $_x->product_id;
  922. }, $soProductIDs);
  923. $soProducts = Product::whereIn('id', $soProductIDs)->get();
  924. $filters = [];
  925. $filters['client'] = $request->input('client');
  926. $filters['product'] = $request->input('product');
  927. $filters['reason'] = $request->input('reason');
  928. $filters['cu_memo'] = $request->input('cu_memo');
  929. $filters['pro_sign'] = $request->input('pro_sign');
  930. $filters['client_sign'] = $request->input('client_sign');
  931. $filters['shipment'] = $request->input('shipment');
  932. $filters['lot_number'] = $request->input('lot_number');
  933. $filters['imei'] = $request->input('imei');
  934. $filters['cancelled'] = $request->input('cancelled');
  935. $supplyOrders = SupplyOrder::where('id', '>', 0);
  936. // apply filters
  937. if ($filters['client']) $supplyOrders->where('client_id', $filters['client']);
  938. if ($filters['product']) $supplyOrders->where('product_id', $filters['product']);
  939. if ($filters['reason']) $supplyOrders->where('reason', 'ILIKE', '%' . $filters['reason'] . '%');
  940. if ($filters['cu_memo']) $supplyOrders->where('cu_memo', 'ILIKE', '%' . $filters['cu_memo'] . '%');
  941. if ($filters['pro_sign']) $supplyOrders->where('is_signed_by_pro', ($filters['pro_sign'] === 'signed'));
  942. if ($filters['client_sign']) {
  943. if ($filters['client_sign'] === 'signed')
  944. $supplyOrders->where('is_signed_by_client', true);
  945. elseif ($filters['client_sign'] === 'waived')
  946. $supplyOrders->where('is_client_signature_waived', true);
  947. else
  948. $supplyOrders->where('is_client_signature_waived', false)->where('is_signed_by_client', false);
  949. }
  950. if ($filters['shipment']) {
  951. if ($filters['shipment'] === 'not_cleared_for_shipment')
  952. $supplyOrders->whereNull('shipment_id')->where('is_cleared_for_shipment', false);
  953. elseif ($filters['shipment'] === 'cleared_for_shipment')
  954. $supplyOrders->whereNull('shipment_id')->where('is_cleared_for_shipment', true);
  955. else
  956. $supplyOrders
  957. ->whereNotNull('shipment_id')
  958. ->whereRaw('(SELECT status FROM shipment WHERE id = shipment_id LIMIT 1) = ?', [$filters['shipment']]);
  959. }
  960. if ($filters['lot_number']) $supplyOrders->where('lot_number', 'ILIKE', '%' . $filters['lot_number'] . '%');
  961. if ($filters['imei']) $supplyOrders->where('imei', 'ILIKE', '%' . $filters['imei'] . '%');
  962. if ($filters['cancelled']) $supplyOrders->where('is_cancelled', ($filters['cancelled'] === 'cancelled'));
  963. $supplyOrders = $supplyOrders->orderBy('created_at', 'desc')->paginate();
  964. return view('app.practice-management.supply-orders',
  965. compact('supplyOrders', 'filters',
  966. 'soClients', 'soProducts', 'counts'
  967. )
  968. );
  969. }
  970. public function shipments(Request $request, $filter = null)
  971. {
  972. // counts
  973. $counts = $this->getShipmentCounts();
  974. // so clients
  975. $shClientIDs = DB::table('shipment')->select('client_id')->distinct()->get()->toArray();
  976. $shClientIDs = array_map(function ($_x) {
  977. return $_x->client_id;
  978. }, $shClientIDs);
  979. $shClients = Client::whereIn('id', $shClientIDs)->get();
  980. $shipments = Shipment::where('id', '>', 0);
  981. $filters = [];
  982. $filters['client'] = $request->input('client');
  983. $filters['courier'] = $request->input('courier');
  984. $filters['tracking_num'] = $request->input('tracking_num');
  985. $filters['label'] = $request->input('label');
  986. $filters['status'] = $request->input('status');
  987. $filters['cancelled'] = $request->input('cancelled');
  988. if ($filters['client']) $shipments->where('client_id', $filters['client']);
  989. if ($filters['courier']) $shipments->where('courier', 'ILIKE', '%' . $filters['courier'] . '%');
  990. if ($filters['tracking_num']) $shipments->where('tracking_number', 'ILIKE', '%' . $filters['tracking_num'] . '%');
  991. if ($filters['label']) {
  992. if ($filters['label'] === 'yes')
  993. $shipments->whereNotNull('label_system_file_id');
  994. else
  995. $shipments->whereNull('label_system_file_id');
  996. }
  997. if ($filters['status']) $shipments->where('status', $filters['status']);
  998. if ($filters['cancelled']) $shipments->where('is_cancelled', ($filters['cancelled'] === 'cancelled'));
  999. $shipments = $shipments->orderBy('created_at', 'desc')->paginate();
  1000. return view('app.practice-management.shipments', compact('shipments', 'filters', 'shClients', 'counts'));
  1001. }
  1002. public function cellularMeasurements(Request $request)
  1003. {
  1004. $measurements = Measurement::orderBy('ts', 'desc')->whereNotNull('ts')->paginate();
  1005. return view('app.practice-management.cellular-measurements', compact('measurements'));
  1006. }
  1007. // v2 supply-orders & shipments management (wh)
  1008. public function supplyOrdersReadyToShip(Request $request)
  1009. {
  1010. $counts = $this->getSupplyOrderCounts();
  1011. $supplyOrders = SupplyOrder
  1012. ::where('is_cleared_for_shipment', true)
  1013. ->where('is_cancelled', false)
  1014. ->whereNull('shipment_id')
  1015. ->join('client', 'client.id', '=', 'supply_order.client_id')
  1016. ->orderBy('client.name_last', 'ASC')
  1017. ->orderBy('client.name_first', 'ASC')
  1018. ->orderBy('supply_order.client_id', 'ASC')
  1019. ->orderBy('supply_order.mailing_address_full', 'ASC')
  1020. ->orderBy('supply_order.created_at', 'ASC')
  1021. ->select('supply_order.*')
  1022. ->paginate();
  1023. return view('app.practice-management.supply-orders-ready-to-ship', compact('supplyOrders', 'counts'));
  1024. }
  1025. public function supplyOrdersShipmentUnderway(Request $request)
  1026. {
  1027. $counts = $this->getSupplyOrderCounts();
  1028. $supplyOrders = SupplyOrder
  1029. ::where('is_cancelled', false)
  1030. ->whereNotNull('shipment_id')
  1031. ->orderBy('client_id', 'ASC')
  1032. ->orderBy('mailing_address_full', 'ASC')
  1033. ->orderBy('created_at', 'ASC')
  1034. ->paginate();
  1035. return view('app.practice-management.supply-orders-shipment-underway', compact('supplyOrders', 'counts'));
  1036. }
  1037. public function supplyOrdersHanging(Request $request)
  1038. {
  1039. $counts = $this->getSupplyOrderCounts();
  1040. $supplyOrders = SupplyOrder
  1041. ::select('supply_order.*')
  1042. ->leftJoin('shipment', function($join) {
  1043. $join->on('supply_order.shipment_id', '=', 'shipment.id');
  1044. })
  1045. ->where('shipment.status', 'CANCELLED')
  1046. ->where('supply_order.is_cancelled', false)
  1047. ->orderBy('supply_order.client_id', 'ASC')
  1048. ->orderBy('supply_order.mailing_address_full', 'ASC')
  1049. ->orderBy('supply_order.created_at', 'ASC')
  1050. ->paginate();
  1051. return view('app.practice-management.supply-orders-hanging', compact('supplyOrders', 'counts'));
  1052. }
  1053. public function supplyOrdersCancelledButUnacknowledged(Request $request)
  1054. {
  1055. $supplyOrders = SupplyOrder::where('signed_by_pro_id', $this->performer()->pro->id)
  1056. ->where('is_cancelled', true)
  1057. ->where('is_cancellation_acknowledged', false)
  1058. ->orderBy('created_at', 'desc')
  1059. ->paginate();
  1060. return view('app.practice-management.supply-orders-cancelled-but-unacknowledged', compact('supplyOrders'));
  1061. }
  1062. public function supplyOrdersUnsigned(Request $request)
  1063. {
  1064. $supplyOrders = SupplyOrder
  1065. ::where('is_cancelled', false)
  1066. ->where('is_signed_by_pro', false)
  1067. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session WHERE pro_id = ?)', [$this->performer()->pro->id])
  1068. ->orderBy('created_at', 'desc')
  1069. ->paginate();
  1070. return view('app.practice-management.supply-orders-unsigned', compact('supplyOrders'));
  1071. }
  1072. private function getSupplyOrderCounts()
  1073. {
  1074. return [
  1075. "supplyOrders" => SupplyOrder::count(),
  1076. "supplyOrdersReadyToShip" => SupplyOrder
  1077. ::where('is_cleared_for_shipment', true)
  1078. ->where('is_cancelled', false)
  1079. ->whereNull('shipment_id')->count(),
  1080. "supplyOrdersShipmentUnderway" => SupplyOrder
  1081. ::where('is_cancelled', false)
  1082. ->whereNotNull('shipment_id')->count(),
  1083. "supplyOrdersHanging" => SupplyOrder
  1084. ::leftJoin('shipment', function($join) {
  1085. $join->on('supply_order.shipment_id', '=', 'shipment.id');
  1086. })
  1087. ->where('shipment.status', 'CANCELLED')
  1088. ->where('supply_order.is_cancelled', false)
  1089. ->count(),
  1090. ];
  1091. }
  1092. public function shipmentsReadyToPrint(Request $request)
  1093. {
  1094. $counts = $this->getShipmentCounts();
  1095. $shipments = Shipment
  1096. ::where('is_cancelled', false)
  1097. ->where('status', 'CREATED')
  1098. ->orderBy('created_at', 'ASC')
  1099. ->paginate();
  1100. return view('app.practice-management.shipments-ready-to-print', compact('shipments', 'counts'));
  1101. }
  1102. public function shipmentsShipmentUnderway(Request $request)
  1103. {
  1104. $counts = $this->getShipmentCounts();
  1105. $shipments = Shipment
  1106. ::where('is_cancelled', false)
  1107. ->where('status', 'PRINTED')
  1108. ->orderBy('created_at', 'ASC')
  1109. ->paginate();
  1110. return view('app.practice-management.shipments-waiting-for-picker', compact('shipments', 'counts'));
  1111. }
  1112. private function getShipmentCounts()
  1113. {
  1114. return [
  1115. "shipments" => Shipment::count(),
  1116. "shipmentsReadyToPrint" => Shipment
  1117. ::where('is_cancelled', false)
  1118. ->where('status', 'CREATED')
  1119. ->count(),
  1120. "shipmentsWaitingForPicker" => Shipment
  1121. ::where('is_cancelled', false)
  1122. ->where('status', 'PRINTED')
  1123. ->count()
  1124. ];
  1125. }
  1126. public function shipment(Request $request, Shipment $shipment)
  1127. {
  1128. return view('app.practice-management.shipment', compact('shipment'));
  1129. }
  1130. public function shipmentsMultiPrint(Request $request, $ids)
  1131. {
  1132. $ids = array_map(function ($_x) {
  1133. return intval($_x);
  1134. }, explode("|", $ids));
  1135. $shipments = Shipment::whereIn('id', $ids)->get();
  1136. return view('app.practice-management.shipments-multi-print', compact('shipments'));
  1137. }
  1138. public function patientClaimSummary(Request $request, $proUid = null)
  1139. {
  1140. $notesTotal = DB::select(DB::raw("SELECT COUNT(*) FROM note WHERE is_cancelled IS NOT TRUE"))[0]->count;
  1141. $notesTotalWithBillingClosed = DB::select(DB::raw("SELECT COUNT(*) FROM note WHERE is_cancelled IS NOT TRUE AND is_bill_closed IS TRUE"))[0]->count;
  1142. $notesTotalWithClaimingClosed = DB::select(DB::raw("SELECT COUNT(*) FROM note WHERE is_cancelled IS NOT TRUE AND is_claim_closed IS TRUE"))[0]->count;
  1143. $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;
  1144. $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;
  1145. $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;
  1146. $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;
  1147. $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;
  1148. $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;
  1149. $performerPro = $this->performer->pro;
  1150. $allPros = [];
  1151. if ($performerPro->pro_type == 'ADMIN') {
  1152. $allPros = Pro::all();
  1153. } else {
  1154. $allPros = [$performerPro];
  1155. }
  1156. //Patient | MCP | # Notes Total | # Notes without Billing Closed | # Notes without Claiming Closed
  1157. $patientsQuery = Client::where('is_dummy', '=', false)
  1158. ->whereNull('shadow_pro_id')
  1159. ->select('id', 'uid', 'name_first', 'name_last', 'mcp_pro_id', 'is_part_b_primary', 'medicare_advantage_plan',
  1160. DB::raw("(SELECT name_first||' '||name_last FROM pro where pro.id = client.mcp_pro_id) as mcp"),
  1161. DB::raw("(SELECT uid FROM pro where pro.id = mcp_pro_id) as mcp_pro_uid"),
  1162. DB::raw("(SELECT COUNT(*) FROM note where note.client_id = client.id) as notes_total"),
  1163. DB::raw("(SELECT COUNT(*) FROM note where note.client_id = client.id AND is_bill_closed IS NOT true) as notes_without_billing_closed"),
  1164. DB::raw("(SELECT COUNT(*) FROM note where note.client_id = client.id AND is_claim_closed IS NOT true) as notes_without_claiming_closed")
  1165. )->orderBy('is_part_b_primary', 'asc')->orderBy('notes_without_claiming_closed', 'desc');
  1166. if ($proUid) {
  1167. $mcpPro = Pro::where('uid', $proUid)->first();
  1168. if ($mcpPro) {
  1169. $patientsQuery->where('client.mcp_pro_id', '=', $mcpPro->id);
  1170. }
  1171. }
  1172. $patientsQuery->whereRaw('(SELECT COUNT(*) FROM note where note.client_id = client.id) > 0');
  1173. $patientsQuery->orderBy('notes_total', 'DESC');
  1174. $patients = $patientsQuery->paginate(50);
  1175. $data = [
  1176. 'patients' => $patients,
  1177. 'proUid' => $proUid,
  1178. 'allPros' => $allPros,
  1179. 'notesTotal' => $notesTotal,
  1180. 'notesTotalWithBillingClosed' => $notesTotalWithBillingClosed,
  1181. 'notesTotalWithClaimingClosed' => $notesTotalWithClaimingClosed,
  1182. 'notes3rdPartyTotal' => $notes3rdPartyTotal,
  1183. 'notes3rdPartyTotalWithBillingClosed' => $notes3rdPartyTotalWithBillingClosed,
  1184. 'notes3rdPartyTotalWithClaimingClosed' => $notes3rdPartyTotalWithClaimingClosed,
  1185. 'patientsTotal' => $patientsTotal,
  1186. 'patientsTotalWithBillingClosed' => $patientsTotalWithBillingClosed,
  1187. 'patientsTotalWithClaimingClosed' => $patientsTotalWithClaimingClosed
  1188. ];
  1189. return view('app.practice-management.patient-claim-summary', $data);
  1190. }
  1191. public function claims(Request $request){
  1192. $status = $request->get('status');
  1193. $claims = [];
  1194. if(!$status){
  1195. $claims = Claim::orderBy('created_at', 'DESC')->paginate();
  1196. }else{
  1197. $claims = Claim::where('status', $status)->orderBy('created_at', 'DESC')->paginate();
  1198. }
  1199. return view('app.practice-management.claims', compact('claims', 'status'));
  1200. }
  1201. public function processClaims(Request $request) {
  1202. $status = '';
  1203. $q = $request->input('q') ? $request->input('q') : '';
  1204. $from = $request->input('from') ? $request->input('from') : '1900-01-01';
  1205. $to = $request->input('to') ? $request->input('to') : '2100-01-01';
  1206. $params = [
  1207. 'q' => '%' . $q . '%',
  1208. 'from' => $from,
  1209. 'to' => $to
  1210. ];
  1211. $hcpPro = $request->input('hcp') ? Pro::where('uid', $request->input('hcp'))->first() : null;
  1212. if($hcpPro) {
  1213. $params['hcp'] = $hcpPro->id;
  1214. }
  1215. $claims = DB::select(DB::raw("
  1216. SELECT claim.uid AS uid,
  1217. DATE(claim.created_at) AS created,
  1218. claim.status,
  1219. client.uid AS client_uid,
  1220. client.cell_number AS client_phone,
  1221. (client.name_last || ' ' || client.name_first) AS client ,
  1222. client.chart_number AS client_chart_number,
  1223. cp.id AS claim_pro_id,
  1224. (cp.name_last || ' ' || cp.name_first) AS claim_pro,
  1225. sp.id AS status_pro_id,
  1226. (sp.name_last || ' ' || sp.name_first) AS status_pro,
  1227. note.uid AS note_uid,
  1228. note.method,
  1229. note.new_or_fu_or_na,
  1230. care_month.uid AS care_month_uid,
  1231. -- claim.status_updated_at,
  1232. (DATE(claim.status_updated_at) || ' ' ||
  1233. LPAD(EXTRACT(hour FROM claim.status_updated_at)::text, 2, '0') || ':' ||
  1234. LPAD(EXTRACT(minute FROM claim.status_updated_at)::text, 2, '0')) AS status_updated_at,
  1235. (SELECT string_agg(claim_line.cpt, ', ') FROM claim_line where claim_id = claim.id) AS cpts,
  1236. (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,
  1237. ROUND(claim.expected_total, 3) as expected_total
  1238. FROM claim
  1239. join client on claim.client_id = client.id
  1240. join pro cp on claim.pro_id = cp.id
  1241. left join note on claim.note_id = note.id
  1242. left join care_month on claim.care_month_id = care_month.id
  1243. left join app_session on claim.status_updated_by_session_id = app_session.id
  1244. left join pro sp on app_session.pro_id = sp.id
  1245. --WHERE claim.status IS NULL OR claim.status = 'NEW'
  1246. WHERE (claim.status is NULL OR claim.status NOT IN ('CANCELLED', 'ABANDONED'" . ($request->input('show-submitted') ? "" : ", 'SUBMITTED'") . "))
  1247. -- AND claim.current_version_id IS NOT NULL
  1248. AND (client.name_first ILIKE :q OR
  1249. client.name_last ILIKE :q OR
  1250. client.chart_number ILIKE :q OR
  1251. client.mcn ILIKE :q)
  1252. AND (claim.created_at >= :from AND claim.created_at <= :to)
  1253. " . ($hcpPro ? "AND claim.pro_id = :hcp" : '') . "
  1254. AND claim.id IN (SELECT mb_claim.claim_id FROM mb_claim)
  1255. ORDER BY claim.created_at DESC
  1256. --OFFSET 0 LIMIT 15
  1257. "), $params);
  1258. if($request->input('json')) {
  1259. return json_encode($claims);
  1260. }
  1261. return view('app.practice-management.process-claims', compact('claims', 'status'));
  1262. }
  1263. public function rmLaunchAndClean(Request $request) {
  1264. $keyNumbers = [];
  1265. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP_PLUS_40'] = CareMonth::where('is_bill_closed', false)
  1266. ->whereNotNull('company_pro_id')
  1267. ->whereNotNull('company_pro_payer_id')
  1268. ->whereNotNull('company_location_id')
  1269. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  1270. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  1271. ->where('rm_total_time_in_seconds', '>=', 4200) // at 4200 (70 minutes, it becomes eligible for plus40)
  1272. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  1273. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  1274. ->whereRaw('(has_anyone_interacted_with_client_about_rm_outside_note IS TRUE OR has_mcp_rm_interacted_by_note IS TRUE )')
  1275. ->count();
  1276. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP_PLUS_40_ifHadInteraction'] = CareMonth::where('is_bill_closed', false)
  1277. ->whereNotNull('company_pro_id')
  1278. ->whereNotNull('company_pro_payer_id')
  1279. ->whereNotNull('company_location_id')
  1280. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  1281. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  1282. ->where('rm_total_time_in_seconds', '>=', 4200) // at 4200 (70 minutes, it becomes eligible for plus40)
  1283. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  1284. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  1285. ->whereRaw('(has_anyone_interacted_with_client_about_rm_outside_note IS NOT TRUE AND has_mcp_rm_interacted_by_note IS NOT TRUE AND is_rm_interaction_waived IS NOT TRUE )')
  1286. ->count();
  1287. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP_PLUS_20'] = CareMonth::where('is_bill_closed', false)
  1288. ->whereNotNull('company_pro_id')
  1289. ->whereNotNull('company_pro_payer_id')
  1290. ->whereNotNull('company_location_id')
  1291. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  1292. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  1293. ->where('rm_total_time_in_seconds', '<', 4200)
  1294. ->where('rm_total_time_in_seconds', '>=', 3000) // at 3000 (50 minutes, it becomes eligible for plus20)
  1295. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  1296. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  1297. ->whereRaw('(has_anyone_interacted_with_client_about_rm_outside_note IS TRUE OR has_mcp_rm_interacted_by_note IS TRUE)')
  1298. ->count();
  1299. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP_PLUS_20_ifHadInteraction'] = CareMonth::where('is_bill_closed', false)
  1300. ->whereNotNull('company_pro_id')
  1301. ->whereNotNull('company_pro_payer_id')
  1302. ->whereNotNull('company_location_id')
  1303. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  1304. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  1305. ->where('rm_total_time_in_seconds', '<', 4200)
  1306. ->where('rm_total_time_in_seconds', '>=', 3000) // at 3000 (50 minutes, it becomes eligible for plus20)
  1307. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  1308. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  1309. ->whereRaw('(has_anyone_interacted_with_client_about_rm_outside_note IS NOT TRUE AND has_mcp_rm_interacted_by_note IS NOT TRUE AND is_rm_interaction_waived IS NOT TRUE )')
  1310. ->count();
  1311. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP'] = CareMonth::where('is_bill_closed', false)
  1312. ->whereNotNull('company_pro_id')
  1313. ->whereNotNull('company_pro_payer_id')
  1314. ->whereNotNull('company_location_id')
  1315. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  1316. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  1317. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  1318. ->whereRaw('(rm_total_time_in_seconds < 3000 OR (rm_total_time_in_seconds >= 3000 AND is_rm_interaction_waived IS TRUE))')
  1319. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  1320. ->count();
  1321. $keyNumbers['careMonthsEligibleForBillGeneration_RMB'] = CareMonth::where('is_bill_closed', false)
  1322. ->whereNotNull('company_pro_id')
  1323. ->whereNotNull('company_pro_payer_id')
  1324. ->whereNotNull('company_location_id')
  1325. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  1326. ->whereRaw('is_rm_time_waived IS TRUE')
  1327. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  1328. ->count();
  1329. $keyNumbers['careMonthsWith16OrMoreMeasurementDays'] = CareMonth::where('is_bill_closed', false)
  1330. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  1331. ->count();
  1332. $careMonthsWith16PlusMeasurements = CareMonth::where('is_bill_closed', false)
  1333. ->where('number_of_days_with_remote_measurements', '>=', 16 )->get();
  1334. return view('app.practice-management.rm-launch-and-clean', compact('keyNumbers', 'careMonthsWith16PlusMeasurements'));
  1335. }
  1336. public function processNotes(Request $request) {
  1337. $mode = $request->input('mode') ? $request->input('mode') : '1';
  1338. if(($mode < 1 || $mode > 5) && $mode != 8) $mode = 1;
  1339. DB::enableQueryLog(); // Enable query log
  1340. $test = Note::where('is_cancelled', false)
  1341. ->where('is_signed_by_hcp', true)
  1342. ->whereRaw("((detail_json)::json->>'isGood')::text = 'true'")
  1343. ->whereNull('current_note_pickup_for_processing_id')
  1344. ->where('is_billing_marked_done', true)
  1345. ->where('is_bill_closed', true)
  1346. ->where('is_claim_closed', true)
  1347. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0)")
  1348. ->count();
  1349. // var_dump($test);
  1350. // dd(DB::getQueryLog()); // Show results of log
  1351. // exit;
  1352. $counts = [
  1353. "picked" => Note::where('is_cancelled', false)
  1354. ->whereNotNull('current_note_pickup_for_processing_id')
  1355. ->count(),
  1356. "bad" => Note::where('is_cancelled', false)
  1357. ->whereRaw("((detail_json)::json->>'isBad' = 'true')")
  1358. ->count(),
  1359. // not yet signed
  1360. "mode-1" => Note::where('is_cancelled', false)
  1361. ->where('is_signed_by_hcp', false)
  1362. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1363. // ->whereNull('current_note_pickup_for_processing_id')
  1364. ->count(),
  1365. // billing not marked done
  1366. "mode-2" => Note::where('is_cancelled', false)
  1367. ->where('is_signed_by_hcp', true)
  1368. //->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1369. // ->whereNull('current_note_pickup_for_processing_id')
  1370. ->where('is_billing_marked_done', false)
  1371. ->count(),
  1372. // billing not closed
  1373. "mode-3" => Note::where('is_cancelled', false)
  1374. ->where('is_signed_by_hcp', true)
  1375. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1376. // ->whereNull('current_note_pickup_for_processing_id')
  1377. ->where('is_billing_marked_done', true)
  1378. ->where('is_bill_closed', false)
  1379. ->count(),
  1380. // claiming not closed
  1381. "mode-4" => Note::where('is_cancelled', false)
  1382. ->where('is_signed_by_hcp', true)
  1383. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1384. // ->whereNull('current_note_pickup_for_processing_id')
  1385. ->whereRaw("(((detail_json)::json->>'isGood')::text <> 'true' OR ((detail_json)::json->>'isGood')::text IS NULL)")
  1386. ->where('is_billing_marked_done', true)
  1387. ->where('is_bill_closed', true)
  1388. ->where('is_claim_closed', false)
  1389. ->count(),
  1390. // has unsubmitted claims
  1391. "mode-5" => Note::where('is_cancelled', false)
  1392. /*->where('is_signed_by_hcp', true)
  1393. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1394. ->whereNull('current_note_pickup_for_processing_id')
  1395. ->where('is_billing_marked_done', true)
  1396. ->where('is_bill_closed', true)
  1397. ->where('is_claim_closed', true)
  1398. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') > 0")
  1399. */
  1400. ->where('is_signed_by_hcp', true)
  1401. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1402. // ->whereNull('current_note_pickup_for_processing_id')
  1403. ->where('is_billing_marked_done', true)
  1404. ->where('is_bill_closed', true)
  1405. // ->whereRaw("(((detail_json)::json->>'isGood')::text <> 'true')")
  1406. ->where('is_claim_closed', true)
  1407. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') > 0)")
  1408. ->count(),
  1409. // has unsubmitted claims MARKED GOOD!
  1410. "mode-8" => Note::where('is_cancelled', false)
  1411. ->where('is_signed_by_hcp', true)
  1412. ->whereRaw("((detail_json)::json->>'isGood')::text = 'true'")
  1413. ->whereNull('current_note_pickup_for_processing_id')
  1414. ->where('is_billing_marked_done', true)
  1415. ->where('is_bill_closed', true)
  1416. ->where('is_claim_closed', false)
  1417. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0)")
  1418. ->count(),
  1419. // all good
  1420. "mode-6" => Note::where('is_cancelled', false)
  1421. ->where('is_signed_by_hcp', true)
  1422. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1423. // ->whereNull('current_note_pickup_for_processing_id')
  1424. ->where('is_billing_marked_done', true)
  1425. ->where('is_bill_closed', true)
  1426. ->where('is_claim_closed', true)
  1427. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id) > 0)")
  1428. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0)")
  1429. ->count(),
  1430. "mode-7" => Note::where('is_cancelled', false)
  1431. ->whereRaw("(detail_json)::json->>'isBad' = 'true'")
  1432. ->count(),
  1433. ];
  1434. return view('app.practice-management.process-notes', compact('mode', 'counts'));
  1435. }
  1436. public function notesProcessingCenter(Request $request) {
  1437. $notes = Note::where('is_cancelled', false);
  1438. // filters
  1439. $proUid = $request->input('proUid');
  1440. if($proUid) {
  1441. $fPro = Pro::where('uid', $proUid)->first();
  1442. if($fPro) {
  1443. $notes = $notes->where('hcp_pro_id', $fPro->id);
  1444. }
  1445. }
  1446. $proSigned = $request->input('proSigned');
  1447. switch($proSigned) {
  1448. case 'yes': $notes = $notes->where('is_signed_by_hcp', true); break;
  1449. case 'no': $notes = $notes->where('is_signed_by_hcp', '!=', true); break;
  1450. }
  1451. $billingMarkedDone = $request->input('billingMarkedDone');
  1452. switch($billingMarkedDone) {
  1453. case 'yes': $notes = $notes->where('is_billing_marked_done', true); break;
  1454. case 'no': $notes = $notes->where('is_billing_marked_done', '!=', true); break;
  1455. }
  1456. $billingClosed = $request->input('billingClosed');
  1457. switch($billingClosed) {
  1458. case 'yes': $notes = $notes->where('is_bill_closed', true); break;
  1459. case 'no': $notes = $notes->where('is_bill_closed', '!=', true); break;
  1460. }
  1461. $claimingClosed = $request->input('claimingClosed');
  1462. switch($claimingClosed) {
  1463. case 'yes': $notes = $notes->where('is_claim_closed', true); break;
  1464. case 'no': $notes = $notes->where('is_claim_closed', '!=', true); break;
  1465. }
  1466. $allClaimsSubmitted = $request->input('allClaimsSubmitted');
  1467. if($allClaimsSubmitted) {
  1468. // TODO
  1469. }
  1470. $goodBad = $request->input('goodBad');
  1471. switch($goodBad) {
  1472. case 'good': $notes = $notes->whereRaw("(detail_json)::json->>'isBad' = 'false'"); break;
  1473. case 'bad': $notes = $notes->whereRaw("(detail_json)::json->>'isBad' = 'true'"); break;
  1474. case 'unclassified': $notes = $notes->whereRaw("(detail_json)::json->>'isBad' is null"); break;
  1475. }
  1476. $startDate = $request->input('startDate');
  1477. if($startDate) {
  1478. $notes = $notes->where('effective_dateest', '>=', $startDate);
  1479. }
  1480. $endDate = $request->input('endDate');
  1481. if($endDate) {
  1482. $notes = $notes->where('effective_dateest', '<=', $endDate);
  1483. }
  1484. $mcPartB = $request->input('mcPartB');
  1485. if($mcPartB) {
  1486. // TODO
  1487. }
  1488. $notes = $notes->orderBy('effective_dateest')->paginate(10);
  1489. return view('app.practice-management.notes-processing-center', compact('notes'));
  1490. }
  1491. public function getNextNote(Request $request, $mode)
  1492. {
  1493. $note = null;
  1494. switch (+$mode) {
  1495. case 1:
  1496. $note = Note::where('is_cancelled', false)
  1497. ->where('is_signed_by_hcp', false)
  1498. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1499. ->whereNull('current_note_pickup_for_processing_id')
  1500. ->orderBy('effective_dateest', 'DESC')
  1501. ->first();
  1502. break;
  1503. case 2:
  1504. $note = Note::where('is_cancelled', false)
  1505. ->where('is_signed_by_hcp', true)
  1506. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1507. ->whereNull('current_note_pickup_for_processing_id')
  1508. ->where('is_billing_marked_done', false)
  1509. ->orderBy('effective_dateest', 'DESC')
  1510. ->first();
  1511. break;
  1512. case 3:
  1513. $note = Note::where('is_cancelled', false)
  1514. ->where('is_signed_by_hcp', true)
  1515. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1516. ->whereNull('current_note_pickup_for_processing_id')
  1517. ->where('is_billing_marked_done', true)
  1518. ->where('is_bill_closed', false)
  1519. ->orderBy('effective_dateest', 'DESC')
  1520. ->first();
  1521. break;
  1522. case 4: // claiming not closed
  1523. DB::enableQueryLog(); // Enable query log
  1524. $note = Note::where('is_cancelled', false)
  1525. ->where('is_signed_by_hcp', true)
  1526. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1527. ->whereNull('current_note_pickup_for_processing_id')
  1528. ->where('is_billing_marked_done', true)
  1529. ->where('is_bill_closed', true)
  1530. ->whereRaw("(((detail_json)::json->>'isGood')::text <> 'true' OR ((detail_json)::json->>'isGood')::text IS NULL)")
  1531. ->where('is_claim_closed', false)
  1532. ->orderBy('effective_dateest', 'DESC')
  1533. ->first();
  1534. // DB::enableQueryLog(); // Enable query log
  1535. // Your Eloquent query executed by using get()
  1536. // dd(DB::getQueryLog()); // Show results of log
  1537. break;
  1538. case 5:
  1539. $note = Note::where('is_cancelled', false)
  1540. ->where('is_signed_by_hcp', true)
  1541. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1542. ->whereNull('current_note_pickup_for_processing_id')
  1543. ->where('is_billing_marked_done', true)
  1544. ->where('is_bill_closed', true)
  1545. ->where('is_claim_closed', true)
  1546. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') > 0")
  1547. ->orderBy('effective_dateest', 'DESC')
  1548. ->first();
  1549. break;
  1550. case 8:
  1551. $note = Note::where('is_cancelled', false)
  1552. ->where('is_signed_by_hcp', true)
  1553. ->whereRaw("((detail_json)::json->>'isGood')::text = 'true'")
  1554. ->whereNull('current_note_pickup_for_processing_id')
  1555. ->where('is_billing_marked_done', true)
  1556. ->where('is_bill_closed', true)
  1557. ->where('is_claim_closed', false)
  1558. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0)")
  1559. ->orderBy('effective_dateest', 'DESC')
  1560. ->first();
  1561. break;
  1562. }
  1563. if($note) {
  1564. $note->client_uid = $note->client->uid;
  1565. }
  1566. return json_encode($note);
  1567. }
  1568. public function pickedNotes(Request $request) {
  1569. $counts = [
  1570. "unpicked" => Note::where('is_cancelled', false)
  1571. ->whereNull('current_note_pickup_for_processing_id')
  1572. ->count(),
  1573. ];
  1574. $notes = Note::where('is_cancelled', false)
  1575. ->whereNotNull('current_note_pickup_for_processing_id')
  1576. ->orderBy('effective_dateest', 'ASC')
  1577. ->paginate();
  1578. return view('app.practice-management.picked-notes', compact('counts', 'notes'));
  1579. }
  1580. public function badNotes(Request $request) {
  1581. $counts = [
  1582. "unpicked" => Note::where('is_cancelled', false)
  1583. ->whereNull('current_note_pickup_for_processing_id')
  1584. ->count(),
  1585. ];
  1586. $notes = Note::where('is_cancelled', false)
  1587. ->whereRaw("(detail_json)::json->>'isBad' = 'true'")
  1588. ->orderBy('effective_dateest', 'ASC')
  1589. ->paginate();
  1590. return view('app.practice-management.bad-notes', compact('counts', 'notes'));
  1591. }
  1592. public function doneNotes(Request $request) {
  1593. $counts = [
  1594. "unpicked" => Note::where('is_cancelled', false)
  1595. ->whereNull('current_note_pickup_for_processing_id')
  1596. ->count(),
  1597. ];
  1598. $notes = Note::where('is_cancelled', false)
  1599. ->where('is_signed_by_hcp', true)
  1600. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1601. ->whereNull('current_note_pickup_for_processing_id')
  1602. ->where('is_billing_marked_done', true)
  1603. ->where('is_bill_closed', true)
  1604. ->where('is_claim_closed', true)
  1605. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id) > 0")
  1606. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0")
  1607. ->orderBy('effective_dateest', 'ASC')
  1608. ->paginate();
  1609. return view('app.practice-management.done-notes', compact('counts', 'notes'));
  1610. }
  1611. public function currentMbClaim(Request $request, $claimUid) {
  1612. $claim = Claim::where('uid', $claimUid)->first();
  1613. return json_encode(MBClaim::where('claim_version_id', $claim->currentVersion->id)->first());
  1614. }
  1615. public function currentClaimLines(Request $request, $claimUid) {
  1616. $claim = Claim::where('uid', $claimUid)->first();
  1617. if($request->input('json')) {
  1618. foreach ($claim->lines as $line) {
  1619. $line->expected_total = round($line->expected_total, 3);
  1620. $x = $line->claimLineIcds;
  1621. }
  1622. return json_encode($claim->lines);
  1623. }
  1624. return view('app.practice-management._claim-lines', compact('claim'));
  1625. }
  1626. public function packsMultiPrint(Request $request) {
  1627. $packs = Pack
  1628. ::select('pack.*')
  1629. ->leftJoin('shipment', function($join) {
  1630. $join->on('pack.shipment_id', '=', 'shipment.id');
  1631. })
  1632. ->whereNotIn('shipment.status', ['CANCELLED', 'DISPATCHED'])
  1633. ->where(function ($query) {
  1634. $query->where('pack.status', '<>', 'DELETED')->orWhereNull('pack.status'); // weird, but just the <> isn't working!
  1635. })
  1636. ->whereNotNull('pack.label_system_file_id')
  1637. ->orderBy('pack.created_at', 'ASC')
  1638. ->get();
  1639. return view('app.practice-management.packs-multi-print', compact('packs'));
  1640. }
  1641. public function packsMultiPDF(Request $request, $ids) {
  1642. $ids = array_map(function ($_x) {
  1643. return intval($_x);
  1644. }, explode("|", $ids));
  1645. $packs = Pack::whereIn('id', $ids)->get();
  1646. }
  1647. public function handouts(Request $request) {
  1648. $handouts = Handout::orderBy('display_name')->get();
  1649. return view('app.practice-management.handouts', compact('handouts'));
  1650. }
  1651. private function callJava($request, $endPoint, $data)
  1652. {
  1653. $url = config('stag.backendUrl') . $endPoint;
  1654. $response = Http::asForm()
  1655. ->withHeaders([
  1656. 'sessionKey' => $request->cookie('sessionKey')
  1657. ])
  1658. ->post($url, $data)
  1659. ->body();
  1660. dd($response);
  1661. return $response;
  1662. }
  1663. public function genericBills(Request $request)
  1664. {
  1665. return view('app.practice-management.generic-bills');
  1666. }
  1667. public function billsUnderProcessing(Request $request)
  1668. {
  1669. $bills = Bill::where('is_cancelled', false)
  1670. ->where(function ($query) { // mcp of any client program and program OB pending
  1671. $query
  1672. ->where(function ($_query) {
  1673. $_query->where('hcp_pro_id', $this->pro->id)
  1674. ->where('hcp_expected_payment_amount', '>', 0)
  1675. ->where('has_hcp_been_paid', false)
  1676. ->where('is_signed_by_hcp', true);
  1677. })
  1678. ->orWhere(function ($_query) {
  1679. $_query->where('cm_pro_id', $this->pro->id)
  1680. ->where('cm_expected_payment_amount', '>', 0)
  1681. ->where('has_cm_been_paid', false)
  1682. ->where('is_signed_by_cm', true);
  1683. })
  1684. ->orWhere(function ($_query) {
  1685. $_query->where('rme_pro_id', $this->pro->id)
  1686. ->where('rme_expected_payment_amount', '>', 0)
  1687. ->where('has_rme_been_paid', false)
  1688. ->where('is_signed_by_rme', true);
  1689. })
  1690. ->orWhere(function ($_query) {
  1691. $_query->where('rmm_pro_id', $this->pro->id)
  1692. ->where('rmm_expected_payment_amount', '>', 0)
  1693. ->where('has_rmm_been_paid', false)
  1694. ->where('is_signed_by_rmm', true);
  1695. })
  1696. ->orWhere(function ($_query) {
  1697. $_query->where('generic_pro_id', $this->pro->id)
  1698. ->where('generic_pro_expected_payment_amount', '>', 0)
  1699. ->where('has_generic_pro_been_paid', false)
  1700. ->where('is_signed_by_generic_pro', true);
  1701. });
  1702. })
  1703. ->orderBy('created_at', 'DESC')
  1704. ->paginate();
  1705. return view('app.practice-management.bills-under-processing', compact('bills'));
  1706. }
  1707. public function careMonthReport(Request $request) {
  1708. $m = $request->input('m');
  1709. $y = $request->input('y');
  1710. if(!$m || !$y) {
  1711. $date = date('Y-m-01');
  1712. }
  1713. else {
  1714. $date = date('Y-m-d', strtotime("$m/1/$y"));
  1715. }
  1716. $pro = $this->pro;
  1717. $records = DB::select("
  1718. SELECT cm.id as care_month_id,
  1719. cm.uid as care_month_uid,
  1720. c.id as client_id,
  1721. c.uid as client_uid,
  1722. cm.number_of_days_with_remote_measurements,
  1723. cm.rm_total_time_in_seconds_by_mcp,
  1724. cm.rm_total_time_in_seconds_by_rme_pro,
  1725. cm.rm_total_time_in_seconds_by_rmm_pro,
  1726. cm.mcp_pro_id,
  1727. cm.rme_pro_id,
  1728. cm.rmm_pro_id,
  1729. (c.name_first || ' ' || c.name_last) as client_name
  1730. FROM care_month cm
  1731. JOIN client c on cm.client_id = c.id
  1732. WHERE cm.start_date = :startDate
  1733. AND (cm.mcp_pro_id = :proID OR
  1734. cm.rme_pro_id = :proID OR
  1735. cm.rmm_pro_id = :proID)
  1736. ORDER BY c.name_last, c.name_first
  1737. ",
  1738. ['startDate' => $date, 'proID' => $pro->id]
  1739. );
  1740. return view('app.practice-management.care-month-report', compact('records', 'date'));
  1741. }
  1742. public function myTeams(Request $request) {
  1743. $pro = $this->pro;
  1744. // get all teams where the authed-pro is the assistant pro
  1745. $teams = ProTeam::where('assistant_pro_id', $pro->id)
  1746. ->where('is_active', true)
  1747. ->orderBy('slug')
  1748. ->get();
  1749. return view('app.practice-management.my-teams', compact('teams'));
  1750. }
  1751. }