Client.php 35 KB

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