Client.php 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Relations\HasOne;
  4. use Illuminate\Support\Collection;
  5. # use Illuminate\Database\Eloquent\Model;
  6. use Illuminate\Support\Facades\DB;
  7. class Client extends Model
  8. {
  9. protected $table = 'client';
  10. public function primaryCoverages()
  11. {
  12. return $this->hasMany(ClientPrimaryCoverage::class, 'client_id', 'id')
  13. ->whereRaw('(is_cancelled IS NULL OR is_cancelled IS FALSE)')
  14. ->orderBy('created_at', 'desc');
  15. }
  16. public function latestManualParentClientPrimaryCoverage(){
  17. return $this->hasOne(ClientPrimaryCoverage::class, 'id', 'latest_manual_parent_client_primary_coverage_id');
  18. }
  19. public function effectiveClientPrimaryCoverage(){
  20. return $this->hasOne(ClientPrimaryCoverage::class, 'id', 'effective_client_primary_coverage_id');
  21. }
  22. public function latestClientPrimaryCoverage(){
  23. return $this->hasOne(ClientPrimaryCoverage::class, 'id', 'latest_client_primary_coverage_id');
  24. }
  25. public function latestNewClientPrimaryCoverage(){
  26. return $this->hasOne(ClientPrimaryCoverage::class, 'id', 'latest_new_client_primary_coverage_id');
  27. }
  28. public function latestAutoRefreshClientPrimaryCoverage(){
  29. return $this->hasOne(ClientPrimaryCoverage::class, 'id', 'latest_auto_refresh_client_primary_coverage_id')
  30. ->whereRaw('(is_cancelled IS NULL OR is_cancelled IS FALSE)');
  31. }
  32. public function latestManualClientPrimaryCoverage(){
  33. return $this->hasOne(ClientPrimaryCoverage::class, 'id', 'latest_manual_client_primary_coverage_id')
  34. ->whereRaw('(is_cancelled IS NULL OR is_cancelled IS FALSE)');
  35. }
  36. public function temporaryOutsiderNewClientPrimaryCoverage(){
  37. return $this->hasOne(ClientPrimaryCoverage::class, 'id', 'temporary_outsider_new_client_primary_coverage_id');
  38. }
  39. public function displayName($_flat = true)
  40. {
  41. $result = '';
  42. if($_flat) {
  43. $result = $this->name_first . ' ' . $this->name_last;
  44. }
  45. else {
  46. $result = $this->name_last . ', ' . $this->name_first;
  47. }
  48. if($this->client_engagement_status_category == 'DUMMY') {
  49. $result .= ' [Test Record]';
  50. }
  51. if($this->client_engagement_status_category == 'DUPLICATE') {
  52. $result .= ' [Duplicate Record]';
  53. }
  54. return $result;
  55. }
  56. public function mcp()
  57. {
  58. return $this->hasOne(Pro::class, 'id', 'mcp_pro_id');
  59. }
  60. public function rd()
  61. {
  62. return $this->hasOne(Pro::class, 'id', 'rd_pro_id');
  63. }
  64. public function pcp()
  65. {
  66. return $this->hasOne(Pro::class, 'id', 'physician_pro_id');
  67. }
  68. public function cm()
  69. {
  70. return $this->hasOne(Pro::class, 'id', 'cm_pro_id');
  71. }
  72. public function rmm()
  73. {
  74. return $this->hasOne(Pro::class, 'id', 'rmm_pro_id');
  75. }
  76. public function rme()
  77. {
  78. return $this->hasOne(Pro::class, 'id', 'rme_pro_id');
  79. }
  80. public function rms()
  81. {
  82. return $this->hasOne(Pro::class, 'id', 'rms_pro_id');
  83. }
  84. public function rmg()
  85. {
  86. return $this->hasOne(Pro::class, 'id', 'rmg_pro_id');
  87. }
  88. public function defaultNaPro()
  89. {
  90. return $this->hasOne(Pro::class, 'id', 'default_na_pro_id');
  91. }
  92. public function creator()
  93. {
  94. return $this->hasOne(Pro::class, 'id', 'created_by_pro_id');
  95. }
  96. public function prosInMeetingWith()
  97. {
  98. return Pro::where('in_meeting_with_client_id', $this->id)->get();
  99. }
  100. public function notes()
  101. {
  102. return $this->hasMany(Note::class, 'client_id', 'id')
  103. // ->where('is_core_note', false)
  104. ->orderBy('effective_dateest', 'desc')
  105. ->orderBy('created_at', 'desc');
  106. }
  107. public function notesPendingClaimsClosed()
  108. {
  109. return $this->hasMany(Note::class, 'client_id', 'id')
  110. ->where('is_claim_closed', false)
  111. ->where('is_signed_by_hcp', true)
  112. ->where('is_cancelled', false)
  113. ->orderBy('effective_dateest', 'desc')
  114. ->orderBy('created_at', 'desc');
  115. }
  116. public function prescriptions()
  117. {
  118. return $this->hasMany(Erx::class, 'client_id', 'id')
  119. /*->where(function ($q) {
  120. $q->whereNull('pro_declared_status')
  121. ->orWhere('pro_declared_status', '<>', 'CANCELLED');
  122. })*/
  123. ->orderBy('created_at', 'desc')
  124. ->orderByRaw('note_id DESC NULLS LAST');
  125. }
  126. public function prescriptionsCreatedInNote($note)
  127. {
  128. return Erx::where('client_id', $this->id)
  129. ->where('note_id', $note->id)
  130. ->orderBy('created_at', 'desc')
  131. ->where(function ($q) {
  132. $q->whereNull('pro_declared_status')
  133. ->orWhere('pro_declared_status', '<>', 'CANCELLED');
  134. })
  135. ->get();
  136. }
  137. public function notesAscending()
  138. {
  139. return $this->hasMany(Note::class, 'client_id', 'id')
  140. ->orderBy('effective_dateest', 'asc')
  141. ->orderBy('created_at', 'desc');;
  142. }
  143. public function mcCodeChecks(){
  144. // $tables = DB::select("SELECT * FROM pg_catalog.pg_tables WHERE schemaname != 'pg_catalog' AND schemaname != 'information_schema'");
  145. // foreach ($tables as $table) {
  146. // dump($table);
  147. // }
  148. // die();
  149. return $this->hasMany(McCodeCheck::class, 'client_id', 'id')->orderBy('created_at', 'asc');
  150. }
  151. public function activeNotes()
  152. {
  153. return $this->hasMany(Note::class, 'client_id', 'id')
  154. ->where('is_cancelled', false)
  155. ->where('id', '<>', $this->core_note_id)
  156. ->orderBy('effective_dateest', 'desc')
  157. ->orderBy('created_at', 'desc');;
  158. }
  159. public function cancelledNotes()
  160. {
  161. return $this->hasMany(Note::class, 'client_id', 'id')
  162. ->where('is_cancelled', true)
  163. ->where('id', '<>', $this->core_note_id)
  164. ->orderBy('effective_dateest', 'desc')
  165. ->orderBy('created_at', 'desc');;
  166. }
  167. public function sections()
  168. {
  169. return $this->hasMany(Section::class, 'client_id', 'id')
  170. ->where('is_active', true)
  171. ->orderBy('created_at', 'asc');
  172. }
  173. public function handouts($note = null)
  174. {
  175. $mappings = HandoutClient::where('client_id', $this->id);
  176. if($note) {
  177. $mappings = $mappings->where('note_id', $note->id);
  178. }
  179. $mappings = $mappings->get();
  180. return $mappings;
  181. // $handouts = new Collection();
  182. // foreach ($mappings as $mapping) {
  183. // $handout = Handout::where('id', $mapping->handout_id)->first();
  184. // $handout->handout_client_uid = $mapping->uid;
  185. // $handouts->add($handout);
  186. // }
  187. // $handouts = $handouts->sortBy('created_at');
  188. // return $handouts;
  189. }
  190. public function duplicateOf()
  191. {
  192. return $this->hasOne(Client::class, 'id', 'duplicate_of_client_id');
  193. }
  194. public function actionItems()
  195. {
  196. return $this->hasMany(ActionItem::class, 'client_id', 'id')
  197. ->orderBy('action_item_category', 'asc')
  198. ->orderBy('created_at', 'desc');
  199. }
  200. public function infoLines()
  201. {
  202. return $this->hasMany(ClientInfoLine::class, 'client_id', 'id')->orderBy('created_at', 'desc');
  203. }
  204. public function measurements()
  205. {
  206. return $this->hasMany(Measurement::class, 'client_id', 'id')
  207. /*->distinct('label')*/
  208. ->where('is_active', true)
  209. ->orderByRaw('ts DESC NULLS LAST');
  210. }
  211. public function cellularMeasurements()
  212. {
  213. return $this->hasMany(Measurement::class, 'client_id', 'id')
  214. /*->distinct('label')*/
  215. ->where('is_active', true)
  216. ->where('is_cellular', true)
  217. ->where('is_cellular_zero', false)
  218. ->orderByRaw('ts DESC NULLS LAST');
  219. }
  220. public function recentMeasurements()
  221. {
  222. return $this->hasMany(Measurement::class, 'client_id', 'id')
  223. ->where('is_active', true)
  224. ->whereNotNull('label')
  225. ->where('label', '<>', 'SBP')
  226. ->where('label', '<>', 'DBP')
  227. ->where('is_cellular_zero', false)
  228. ->orderByRaw('ts DESC NULLS LAST')
  229. ->offset(0)->limit(20);
  230. }
  231. public function nonZeroMeasurements()
  232. {
  233. return $this->hasMany(Measurement::class, 'client_id', 'id')
  234. /*->distinct('label')*/
  235. ->where('is_active', true)
  236. ->where('is_cellular_zero', false)
  237. ->orderBy('effective_date', 'desc');
  238. }
  239. public function getNonZeroBpMeasurements(){
  240. return $this->hasMany(Measurement::class, 'client_id', 'id')
  241. /*->distinct('label')*/
  242. ->where('is_active', true)
  243. ->where('label', '=', 'BP')
  244. ->where('sbp_mm_hg', '>', 0)
  245. ->where('dbp_mm_hg', '>', 0)
  246. ->orderBy('ts', 'desc');
  247. }
  248. public function getNonZeroWeightMeasurements(){
  249. return $this->hasMany(Measurement::class, 'client_id', 'id')
  250. /*->distinct('label')*/
  251. ->where('is_active', true)
  252. ->where('label', '=', 'Wt. (lbs.)')
  253. ->where('numeric_value', '>', 0)
  254. ->orderBy('ts', 'desc');
  255. }
  256. public function currentCareMonth()
  257. {
  258. $cmStartDate = date('Y-m-01');
  259. return CareMonth::where('client_id', $this->id)
  260. ->whereRaw('start_date = ?', [$cmStartDate])
  261. ->first();
  262. }
  263. // returns the current care-month, if in fact patient is awaiting mcp rm interaction
  264. public function isAwaitingRMCommunicationFromMCP() {
  265. // if patient is enrolled in rm AND has current care month AND $careMonth->has_mcp_interacted_with_client_about_rm IS FALSE
  266. if($this->is_enrolled_in_rm !== 'YES') return false;
  267. $careMonth = $this->currentCareMonth();
  268. if(!$careMonth) return false;
  269. return $careMonth->has_mcp_interacted_with_client_about_rm ? false : $careMonth;
  270. }
  271. public function previousCareMonth()
  272. {
  273. $cmStartDate = date('Y-m-d', strtotime('first day of last month'));
  274. return CareMonth
  275. ::where('client_id', $this->id)
  276. ->where('start_date', $cmStartDate)
  277. ->first();
  278. }
  279. public function measurementsInCareMonth(CareMonth $careMonth)
  280. {
  281. $cmStartDate = strtotime($careMonth->start_date);
  282. $month = date("n", $cmStartDate);
  283. $year = date("Y", $cmStartDate);
  284. $measurements = Measurement
  285. ::where('client_id', $this->id)
  286. ->whereRaw('EXTRACT(MONTH FROM effective_date) = ?', [$month])
  287. ->whereRaw('EXTRACT(YEAR FROM effective_date) = ?', [$year])
  288. ->where('is_active', true)
  289. ->orderBy('ts', 'desc')
  290. ->get();
  291. return $measurements;
  292. }
  293. public function allMeasurements()
  294. {
  295. return $this->hasMany(Measurement::class, 'client_id', 'id')
  296. ->where('is_active', true)
  297. ->whereNull('parent_measurement_id')
  298. ->orderBy('label', 'asc')
  299. ->orderBy('effective_date', 'desc');
  300. }
  301. public function smses()
  302. {
  303. return $this->hasMany(ClientSMS::class, 'client_id', 'id')
  304. ->orderBy('created_at', 'desc');
  305. }
  306. public function ismses()
  307. {
  308. return $this->hasMany(Isms::class, 'client_id', 'id')
  309. ->orderBy('created_at', 'desc');
  310. }
  311. public function documents()
  312. {
  313. return $this->hasMany(ClientDocument::class, 'client_id', 'id')
  314. ->orderBy('created_at', 'desc');
  315. }
  316. public function incomingReports() {
  317. return $this->hasMany(IncomingReport::class, 'client_id', 'id')
  318. ->orderBy('created_at', 'desc');
  319. }
  320. public function smsNumbers() {
  321. return $this->hasMany(ClientSMSNumber::class, 'client_id', 'id')
  322. ->orderBy('created_at', 'desc');
  323. }
  324. public function nextMcpAppointment()
  325. {
  326. return $this->hasOne(Appointment::class, 'id', 'next_mcp_appointment_id');
  327. }
  328. public function lastMcpAppointment()
  329. {
  330. return $this->hasOne(Appointment::class, 'id', 'previous_mcp_appointment_id');
  331. }
  332. public function lastMeasurementOfType($_type) {
  333. return Measurement::where('client_id', $this->id)
  334. ->whereNotNull('bdt_measurement_id')
  335. ->whereNotNull('ts')
  336. ->where('is_cellular_zero', false)
  337. ->where('is_active', true)
  338. ->where('label', '=', $_type)
  339. ->orderBy('ts', 'desc')
  340. ->first();
  341. }
  342. public function appointments()
  343. {
  344. return $this->hasMany(Appointment::class, 'client_id', 'id')
  345. ->orderBy('start_time', 'desc');
  346. }
  347. public function appointmentsForProByStatus($forPro = 'all', $status = 'all')
  348. {
  349. $appointments = Appointment::where('client_id', $this->id);
  350. if($forPro !== 'all') {
  351. $forPro = Pro::where('uid', $forPro)->first();
  352. $appointments = $appointments->where('pro_id', $forPro->id);
  353. }
  354. if($status !== 'ALL') {
  355. $appointments = $appointments->where('status', $status);
  356. }
  357. $appointments = $appointments->orderBy('raw_date', 'desc')->orderBy('raw_start_time', 'desc');
  358. return $appointments->get();
  359. }
  360. public function upcomingAppointments()
  361. {
  362. return $this->hasMany(Appointment::class, 'client_id', 'id')
  363. ->where('raw_date', '>=', date('Y-m-d'))
  364. ->whereIn('status', ['PENDING', 'CONFIRMED'])
  365. ->orderBy('start_time', 'desc')
  366. ->limit(5);
  367. }
  368. public function nextAppointment() {
  369. return Appointment
  370. ::where('client_id', $this->id)
  371. ->where('raw_date', '>=', DB::raw('NOW()'))
  372. ->whereIn('status', ['PENDING', 'CONFIRMED'])
  373. ->orderBy('start_time')
  374. ->first();
  375. }
  376. public function appointmentsFromLastWeek()
  377. {
  378. $dateLastWeek = date_sub(date_create(), date_interval_create_from_date_string("14 days"));
  379. $dateLastWeek = date_format($dateLastWeek, "Y-m-d");
  380. return $this->hasMany(Appointment::class, 'client_id', 'id')
  381. ->where('raw_date', '>=', $dateLastWeek)
  382. ->orderBy('start_time', 'desc');
  383. }
  384. public function memos()
  385. {
  386. return $this->hasMany(ClientMemo::class, 'client_id', 'id')
  387. ->where('is_cancelled', false)
  388. ->orderBy('created_at', 'desc');
  389. }
  390. public function devices()
  391. {
  392. return $this->hasMany(ClientBDTDevice::class, 'client_id', 'id')
  393. ->where('is_active', true)
  394. ->orderBy('created_at', 'desc');
  395. }
  396. public function deactivatedDevices()
  397. {
  398. return $this->hasMany(ClientBDTDevice::class, 'client_id', 'id')
  399. ->where('is_active', false)
  400. ->orderBy('created_at', 'desc');
  401. }
  402. public function hasDevice($_device)
  403. {
  404. $count = ClientBDTDevice::where('client_id', $this->id)
  405. ->where('device_id', $_device->id)
  406. ->where('is_active', true)
  407. ->count();
  408. return !!$count;
  409. }
  410. public function deviceMeasurements()
  411. {
  412. return $this->hasMany(ClientBDTMeasurement::class, 'client_id', 'id')
  413. ->orderBy('created_at', 'desc');
  414. }
  415. public function activeMcpRequest()
  416. {
  417. return $this->hasOne(McpRequest::class, 'id', 'active_mcp_request_id');
  418. }
  419. public function clientPrograms()
  420. {
  421. return $this->hasMany(ClientProgram::class, 'client_id', 'id')
  422. ->where('is_active', true)
  423. ->orderBy('title', 'desc');
  424. }
  425. public function tickets()
  426. {
  427. return $this->hasMany(Ticket::class, 'client_id', 'id')
  428. ->orderBy('is_open', 'desc')
  429. ->orderBy('created_at', 'desc');
  430. }
  431. public function mcpDisplayName()
  432. {
  433. }
  434. public function rmeDisplayName()
  435. {
  436. }
  437. public function supplyOrderForCellularBPDevice() {
  438. return SupplyOrder::where('product_id', 1)
  439. ->where('is_cancelled', false)
  440. ->where('client_id', $this->id)
  441. ->orderBy('id', 'desc')
  442. ->first();
  443. }
  444. public function supplyOrderForCellularWeightScale() {
  445. return SupplyOrder::where('product_id', 2)
  446. ->where('is_cancelled', false)
  447. ->where('client_id', $this->id)
  448. ->orderBy('id', 'desc')
  449. ->first();
  450. }
  451. public function firstCellularBPDevice()
  452. {
  453. $devices = $this->devices;
  454. $x = null;
  455. foreach($devices as $device){
  456. if($device->device->category == 'BP'){
  457. $x = $device;
  458. break;
  459. }
  460. }
  461. return $x;
  462. }
  463. public function getFirstCellularBPMeasurementAt()
  464. {
  465. }
  466. public function getLatestCellularBPMeasurementAt()
  467. {
  468. }
  469. public function getTotalCellularBPMeasurements()
  470. {
  471. }
  472. public function firstCellularWeightDevice()
  473. {
  474. $devices = $this->devices;
  475. $x = null;
  476. foreach($devices as $device){
  477. if($device->device->category == 'WEIGHT'){
  478. $x = $device;
  479. break;
  480. }
  481. }
  482. return $x;
  483. }
  484. public function getFirstCellularWeightMeasurementAt()
  485. {
  486. }
  487. public function getLatestCellularWeightMeasurementAt()
  488. {
  489. }
  490. public function getTotalCellularWeightMeasurements()
  491. {
  492. }
  493. public function prosWithAccess()
  494. {
  495. $pros = [];
  496. // directly associated pros
  497. $pro = $this->mcp;
  498. if ($pro && $pro->id) $pros[] = ["pro" => $pro->displayName(), "association" => 'MCP'];
  499. $pro = $this->pcp;
  500. if ($pro && $pro->id) $pros[] = ["pro" => $pro->displayName(), "association" => 'PCP (Physician)'];
  501. $pro = $this->cm;
  502. if ($pro && $pro->id) $pros[] = ["pro" => $pro->displayName(), "association" => 'CM'];
  503. $pro = $this->rmm;
  504. if ($pro && $pro->id) $pros[] = ["pro" => $pro->displayName(), "association" => 'RMM'];
  505. $pro = $this->rme;
  506. if ($pro && $pro->id) $pros[] = ["pro" => $pro->displayName(), "association" => 'RME'];
  507. $pro = $this->defaultNaPro;
  508. if ($pro && $pro->id) $pros[] = ["pro" => $pro->displayName(), "association" => 'Care Coordinator'];
  509. // via client pro access
  510. $cpAccesses = ClientProAccess::where('client_id', $this->id)->where('is_active', true)->get();
  511. foreach ($cpAccesses as $cpAccess) {
  512. if (!$cpAccess->pro) continue;
  513. $pros[] = ["pro" => $cpAccess->pro->displayName(), "association" => $cpAccess->reason_category. ' - Via Client Pro Access', 'isClientProAccess'=>true, 'clientProAccess'=>$cpAccess];
  514. }
  515. // via appointments
  516. $appointments = Appointment::where('client_id', $this->id)->get();
  517. foreach ($appointments as $appointment) {
  518. if (!$appointment->pro) continue;
  519. $pros[] = ["pro" => $appointment->pro->displayName(), "association" => 'Via Appointment: ' . $appointment->raw_date];
  520. }
  521. // via client program
  522. $clientPrograms = ClientProgram::where('client_id', $this->id)->where('is_active', true)->get();
  523. foreach ($clientPrograms as $clientProgram) {
  524. if ($clientProgram->mcp)
  525. $pros[] = ["pro" => $clientProgram->mcp->displayName(), "association" => 'Program MCP: ' . $clientProgram->title];
  526. if ($clientProgram->manager)
  527. $pros[] = ["pro" => $clientProgram->manager->displayName(), "association" => 'Program Manager: ' . $clientProgram->title];
  528. }
  529. // sort by pro name
  530. $name = array_column($pros, 'pro');
  531. array_multisort($name, SORT_ASC, $pros);
  532. return $pros;
  533. }
  534. public function mcpRequests()
  535. {
  536. return $this->hasMany(McpRequest::class, 'for_client_id', 'id')
  537. ->orderBy('created_at', 'desc');
  538. }
  539. public function eligibleRefreshes()
  540. {
  541. return $this->hasMany(ClientEligibleRefresh::class, 'client_id', 'id')
  542. ->orderBy('created_at', 'desc');
  543. }
  544. public function mbPayerValidationResults()
  545. {
  546. return $this->hasMany(ClientMBPayerValidationResult::class, 'client_id', 'id')
  547. ->orderBy('created_at', 'desc');
  548. }
  549. public function payer()
  550. {
  551. return $this->hasOne(MBPayer::class, 'id', 'mb_payer_id');
  552. }
  553. public function supplyOrders()
  554. {
  555. return $this->hasMany(SupplyOrder::class, 'client_id', 'id')
  556. ->orderBy('created_at', 'desc');
  557. }
  558. public function activeSupplyOrders()
  559. {
  560. return $this->hasMany(SupplyOrder::class, 'client_id', 'id')
  561. ->where('is_cancelled', false)
  562. ->orderBy('created_at', 'desc');
  563. }
  564. public function cancelledSupplyOrders()
  565. {
  566. return $this->hasMany(SupplyOrder::class, 'client_id', 'id')
  567. ->where('is_cancelled', true)
  568. ->orderBy('created_at', 'desc');
  569. }
  570. public function readyToShipSupplyOrders()
  571. {
  572. return $this->hasMany(SupplyOrder::class, 'client_id', 'id')
  573. ->where('is_cancelled', false)
  574. ->where('is_cleared_for_shipment', true)
  575. ->whereNull('shipment_id')
  576. ->orderBy('created_at', 'desc');
  577. }
  578. public function shipments()
  579. {
  580. return $this->hasMany(Shipment::class, 'client_id', 'id')
  581. ->where('is_cancelled', false)
  582. ->orderBy('created_at', 'desc');
  583. }
  584. public function numSignedNotes() {
  585. return Note::where('client_id', $this->id)
  586. ->where('is_cancelled', false)
  587. ->where('is_signed_by_hcp', true)
  588. ->count();
  589. }
  590. public function smsReminders()
  591. {
  592. return $this->hasMany(SimpleSMSReminder::class, 'client_id', 'id')
  593. ->orderBy('created_at', 'asc');
  594. }
  595. public function measurementConfirmationNumbers()
  596. {
  597. return $this->hasMany(MeasurementConfirmationNumber::class, 'client_id', 'id')
  598. ->orderBy('created_at', 'asc');
  599. }
  600. public function shadowOfPro() {
  601. return $this->hasOne(Pro::class, 'id', 'shadow_pro_id');
  602. }
  603. public function clientTags()
  604. {
  605. return $this->hasMany(ClientTag::class, 'client_id', 'id')
  606. ->where('is_cancelled', false)
  607. ->orderBy('tag', 'asc');
  608. }
  609. public function medicalTeam()
  610. {
  611. return $this->hasMany(ClientProAccess::class, 'client_id', 'id')
  612. ->where('is_active', true)
  613. ->whereNotNull('pro_id')
  614. ->orderBy('created_at', 'asc');
  615. }
  616. public function accountInvites()
  617. {
  618. return $this->hasMany(AccountInvite::class, 'for_client_id', 'id')
  619. ->orderBy('created_at', 'desc');
  620. }
  621. public function linkedAccounts()
  622. {
  623. return $this->hasMany(AccountClient::class, 'client_id', 'id')
  624. ->orderBy('created_at', 'desc');
  625. }
  626. public function pages($_type, $_returnShadows, $_note) {
  627. return Page
  628. ::where('client_id', $this->id)
  629. ->where('note_id', $_note->id)
  630. ->where('category', $_type)
  631. ->where('is_shadow', !!$_returnShadows)
  632. ->orderBy('key', 'ASC')
  633. ->get();
  634. }
  635. public function firstPageByCategoryAndKey($_category, $_key) {
  636. return Page
  637. ::where('client_id', $this->id)
  638. ->where('category', $_category)
  639. ->where('key', $_key)
  640. ->first();
  641. }
  642. public function cmReasons()
  643. {
  644. return $this->hasMany(ClientCmRmReason::class, 'client_id', 'id')
  645. ->where('cm_or_rm', 'CM')
  646. ->where('is_removed', false)
  647. ->orderBy('position_index', 'ASC')
  648. ->orderBy('code', 'ASC');
  649. }
  650. public function rmReasons()
  651. {
  652. return $this->hasMany(ClientCmRmReason::class, 'client_id', 'id')
  653. ->where('cm_or_rm', 'RM')
  654. ->where('is_removed', false)
  655. ->orderBy('position_index', 'ASC')
  656. ->orderBy('code', 'ASC');
  657. }
  658. public function cmSetupNote()
  659. {
  660. return $this->hasOne(Note::class, 'id', 'cm_setup_note_id');
  661. }
  662. public function rmSetupCareMonth()
  663. {
  664. return $this->hasOne(CareMonth::class, 'id', 'rm_setup_care_month_id');
  665. }
  666. public function defaultMcpCompanyPro()
  667. {
  668. return $this->hasOne(CompanyPro::class, 'id', 'default_mcp_company_pro_id');
  669. }
  670. public function defaultMcpCompanyProPayer()
  671. {
  672. return $this->hasOne(CompanyProPayer::class, 'id', 'default_mcp_company_pro_payer_id');
  673. }
  674. public function defaultMcpCompanyLocation()
  675. {
  676. return $this->hasOne(CompanyLocation::class, 'id', 'default_mcp_company_location_id');
  677. }
  678. public function hasNewNoteForPro($_pro) {
  679. $count = Note::where('client_id', $this->id)->where('hcp_pro_id', $_pro->id)->where('is_cancelled', false)->where('new_or_fu_or_na', 'NEW')->count();
  680. return !!$count;
  681. }
  682. public function systemSourcePro()
  683. {
  684. return $this->hasOne(Pro::class, 'id', 'system_source_pro_id');
  685. }
  686. public function systemSourceProTeam()
  687. {
  688. return $this->hasOne(ProTeam::class, 'id', 'system_source_pro_team_id');
  689. }
  690. public function adminEngagementAssessmentStatus(){
  691. return $this->hasOne(Status::class, 'id', 'admin_engagement_assessment_status_id');
  692. }
  693. public function mcpEngagementAssessmentStatus(){
  694. return $this->hasOne(Status::class, 'id', 'mcp_engagement_assessment_status_id');
  695. }
  696. public function defaultNaEngagementAssessmentStatus(){
  697. return $this->hasOne(Status::class, 'id', 'default_na_engagement_assessment_status_id');
  698. }
  699. public function clientSelfSatisfactionStatus(){
  700. return $this->hasOne(Status::class, 'id', 'client_self_satisfaction_status_id');
  701. }
  702. public function recentNotes($_pro = null) {
  703. $notes = Note::where('client_id', $this->id)->where('is_cancelled', false);
  704. if($_pro) {
  705. $notes = $notes->where('hcp_pro_id', $_pro->id);
  706. }
  707. $notes = $notes->orderBy('effective_dateest', 'DESC')->limit(5)->get();
  708. return $notes;
  709. }
  710. public function cmMeasurementsMatrix($_careMonth, $pro = null) {
  711. $days = [];
  712. $matches = DB::select(
  713. "
  714. SELECT m.id AS measurement_id,
  715. m.uid AS measurement_uid,
  716. cm.id AS care_month_id,
  717. cm.uid AS care_month_uid,
  718. m.label,
  719. m.value,
  720. m.dbp_mm_hg,
  721. m.sbp_mm_hg,
  722. m.value_pulse,
  723. m.value_irregular,
  724. m.numeric_value,
  725. m.effective_date,
  726. m.ts,
  727. m.has_been_stamped_by_mcp,
  728. m.has_been_stamped_by_rmm,
  729. m.has_been_stamped_by_non_hcp
  730. FROM measurement m
  731. JOIN care_month cm ON m.care_month_id = cm.id
  732. WHERE m.care_month_id = :careMonthID
  733. AND m.label NOT IN ('SBP', 'DBP')
  734. AND m.bdt_measurement_id IS NOT NULL
  735. AND m.is_active IS TRUE
  736. AND (m.is_cellular_zero = FALSE or m.is_cellular_zero IS NULL)
  737. AND m.ts IS NOT NULL
  738. AND m.client_bdt_measurement_id IS NOT NULL
  739. ORDER BY m.ts DESC
  740. ",
  741. ['careMonthID' => $_careMonth->id]
  742. );
  743. foreach ($matches as $match) {
  744. $time = (floor($match->ts / 1000));
  745. $realTimezone = resolve_timezone('EASTERN');
  746. $date = new \DateTime("@$time");
  747. $date->setTimezone(new \DateTimeZone($realTimezone));
  748. $match->date = $date->format("m/d/Y");
  749. $match->dateYMD = $date->format("Y-m-d");
  750. $match->time = $date->format("h:i A");
  751. // get existing entries for listing
  752. $match->entries = CareMonthEntry::where('care_month_id', $match->care_month_id)
  753. ->where('is_removed', false)
  754. ->where('effective_date', $match->dateYMD);
  755. if(!!$pro) {
  756. $match->entries = $match->entries->where('pro_id', $pro->id);
  757. }
  758. $match->entries = $match->entries->orderBy('created_at')->get();
  759. if(!isset($days[$match->date])) {
  760. $days[$match->date] = [];
  761. }
  762. $days[$match->date][] = $match;
  763. }
  764. return $days;
  765. }
  766. public function getPrimaryCoverage()
  767. {
  768. return $this->effectiveClientPrimaryCoverage;
  769. }
  770. // return value will be YES, NO or UNKNOWN
  771. public function getPrimaryCoverageStatus() {
  772. $coverage = $this->getPrimaryCoverage();
  773. if(!$coverage) return 'NO';
  774. return $coverage->getStatus();
  775. }
  776. public function getMcpAssignedOn() {
  777. $change = ClientProChange::where('client_id', $this->id)
  778. ->where('new_pro_id', $this->mcp_pro_id)
  779. ->where('responsibility_type', 'MCP')
  780. ->orderBy('created_at', 'DESC')
  781. ->first();
  782. if(!!$change) {
  783. return friendlier_date($change->created_at);
  784. }
  785. return '-';
  786. }
  787. public function coreNote(){
  788. return $this->hasOne(Note::class, 'id', 'core_note_id');
  789. }
  790. public function mostRecentCompletedMcpNote(){
  791. return $this->hasOne(Note::class, 'id', 'most_recent_completed_mcp_note_id');
  792. }
  793. public function nonCoreVisitNotes() {
  794. return $this->hasMany(Note::class, 'client_id', 'id')
  795. ->where('id', '<>', $this->core_note_id)
  796. ->whereNotNull('visit_template_id')
  797. ->orderBy('created_at', 'desc');
  798. }
  799. public function clientProChanges() {
  800. return $this->hasMany(ClientProChange::class, 'client_id', 'id')
  801. ->orderBy('created_at', 'desc');
  802. }
  803. public function mostRecentWeightMeasurement(){
  804. return $this->hasOne(Measurement::class, 'id', 'most_recent_weight_measurement_id');
  805. }
  806. public function hasBPDevice() {
  807. $cbds = ClientBDTDevice::where('client_id', $this->id)->get();
  808. foreach ($cbds as $cbd) {
  809. if($cbd->is_active && !!$cbd->device && $cbd->device->is_active && $cbd->device->category === 'BP') return true;
  810. }
  811. return false;
  812. }
  813. public function hasWeightScaleDevice() {
  814. $cbds = ClientBDTDevice::where('client_id', $this->id)->get();
  815. foreach ($cbds as $cbd) {
  816. if($cbd->is_active && !!$cbd->device && $cbd->device->is_active && $cbd->device->category === 'WEIGHT') return true;
  817. }
  818. return false;
  819. }
  820. public function clientEngagementStatus(){
  821. return $this->hasOne(Status::class, 'id', 'client_engagement_status_id');
  822. }
  823. public function clientBpWeightPhoneNumberStatus(){
  824. return $this->hasOne(ClientBpWeightPhoneNumberStatus::class, 'id', 'client_bp_weight_phone_number_status_id');
  825. }
  826. public function getDeviceDeliveryStatus($productId){
  827. $result = DB::select("SELECT sh.status FROM shipment sh LEFT JOIN supply_order so ON so.shipment_id = sh.id WHERE so.product_id = ".$productId." AND so.client_id = ".$this->id." ORDER BY sh.created_at DESC LIMIT 1");
  828. if (count($result)){
  829. return $result[0]->status;
  830. }
  831. return '';
  832. }
  833. public function hasDataInCanvas($_type) {
  834. $page = Page::where('client_id', $this->id)->where('category', 'CANVAS')->where('key', $_type)->first();
  835. $contentData = [];
  836. if($page){
  837. $contentData = json_decode($page->data, true);
  838. }else{
  839. if($this->canvas_data) {
  840. $canvasData = json_decode($this->canvas_data, true);
  841. if(isset($canvasData[$_type])) {
  842. $contentData = $canvasData[$_type];
  843. if($_type !== 'vitals') {
  844. if(!isset($contentData['items'])){
  845. $contentData['items'] = [];
  846. }
  847. }
  848. }
  849. }
  850. }
  851. if($_type !== 'vitals') {
  852. if (isset($contentData['items']) && count($contentData['items'])) {
  853. return true;
  854. }
  855. }
  856. else {
  857. foreach ($contentData as $cd) {
  858. if(isset($cd['value']) && !empty($cd['value'])) return true;
  859. }
  860. }
  861. return false;
  862. }
  863. // 4 Infra-red Temperature gun
  864. public function temparatureGunDeliveryStatus(){
  865. return $this->getDeviceDeliveryStatus(4);
  866. }
  867. // 3 Pulse Oximeter (
  868. public function pulseOximeterDeliveryStatus(){
  869. return $this->getDeviceDeliveryStatus(3);
  870. }
  871. // 1 Cellular BP - Standard Arm Cuff (if delivered, then it should show its status as Delivered, Dispatched, In-transit, Returned)
  872. public function cellularBPDeliveryStatus(){
  873. return $this->getDeviceDeliveryStatus(1);
  874. }
  875. // 2 Weight scale
  876. public function weightScaleDeliveryStatus(){
  877. return $this->getDeviceDeliveryStatus(2);
  878. }
  879. public function carePlanFlaggedBy(){
  880. return $this->hasOne(Pro::class, 'id', 'flagged_by_pro_id');
  881. }
  882. public function carePlanFlagAcknowledgedBy(){
  883. return $this->hasOne(Pro::class, 'id', 'flag_acknowledged_by_pro_id');
  884. }
  885. }