PracticeManagementController.php 85 KB

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