Pro.php 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238
  1. <?php
  2. namespace App\Models;
  3. # use Illuminate\Database\Eloquent\Model;
  4. use App\Helpers\TimeLine;
  5. use DateTime;
  6. use Exception;
  7. use Illuminate\Support\Facades\DB;
  8. class Pro extends Model
  9. {
  10. protected $table = 'pro';
  11. public function displayName() {
  12. $name = [];
  13. if(!empty($this->name_display)) return $this->name_display;
  14. if(!empty($this->name_last)) $name[] = $this->name_last;
  15. if(!empty($this->name_first)) $name[] = $this->name_first;
  16. if(!count($name)) {
  17. $name = $this->name_display;
  18. }
  19. else {
  20. $name = implode(", ", $name);
  21. }
  22. return $name;
  23. }
  24. public function initials() {
  25. $characters = [];
  26. if(!empty($this->name_first)) $characters[] = $this->name_first[0];
  27. if(!empty($this->name_last)) $characters[] = $this->name_last[0];
  28. return strtolower(implode("", $characters));
  29. }
  30. public function debitBills()
  31. {
  32. return $this->hasMany(Bill::class, 'debit_pro_id');
  33. }
  34. public function cmBills()
  35. {
  36. return $this->hasMany(Bill::class, 'cm_pro_id');
  37. }
  38. public function hcpBills()
  39. {
  40. return $this->hasMany(Bill::class, 'hcp_pro_id');
  41. }
  42. public function teamsWhereAssistant()
  43. {
  44. return $this->hasMany(ProTeam::class, 'assistant_pro_id', 'id');
  45. }
  46. public function isDefaultNA()
  47. {
  48. return $this->is_considered_for_dna;
  49. }
  50. public function lastPayment() {
  51. return ProTransaction
  52. ::where('pro_id', $this->id)
  53. ->where('plus_or_minus', 'PLUS')
  54. ->orderBy('created_at', 'desc')
  55. ->first();
  56. }
  57. public function hasRates() {
  58. $numRates = ProRate::where('is_active', true)->where('pro_id', $this->id)->count();
  59. return $numRates > 0;
  60. }
  61. public function cmRates() {
  62. return ProRate::distinct('code')
  63. ->where('is_active', true)
  64. ->where('pro_id', $this->id)
  65. ->where('code', 'LIKE', 'CM%')
  66. ->get();
  67. }
  68. public function rmRates() {
  69. return ProRate::distinct('code')
  70. ->where('is_active', true)
  71. ->where('pro_id', $this->id)
  72. ->where('code', 'LIKE', 'RM%')
  73. ->get();
  74. }
  75. public function noteRates() {
  76. return ProRate::distinct('code')
  77. ->where('is_active', true)
  78. ->where('pro_id', $this->id)
  79. ->where('code', 'NOT LIKE', 'CM%')
  80. ->where('code', 'NOT LIKE', 'RM%')
  81. ->where('responsibility', '<>', 'GENERIC')
  82. ->get();
  83. }
  84. public function genericRates() {
  85. return ProRate::distinct('code')
  86. ->where('is_active', true)
  87. ->where('pro_id', $this->id)
  88. ->where('responsibility', 'GENERIC')
  89. ->get();
  90. }
  91. public function recentDebits() {
  92. return ProTransaction
  93. ::where('pro_id', $this->id)
  94. ->where('plus_or_minus', 'PLUS')
  95. ->orderBy('created_at', 'desc')
  96. ->skip(0)->take(4)->get();
  97. }
  98. public function shortcuts() {
  99. return $this->hasMany(ProTextShortcut::class, 'pro_id')->where('is_removed', false);
  100. }
  101. public function allShortcuts() {
  102. $myId = $this->id;
  103. $shortcuts = ProTextShortcut::where('is_removed', false)
  104. ->where(function ($query2) use ($myId) {
  105. $query2
  106. ->where('pro_id', $myId)
  107. ->orWhereNull('pro_id');
  108. })
  109. ->orderBy('shortcut')
  110. ->get();
  111. return $shortcuts;
  112. }
  113. public function noteTemplates() {
  114. return $this->hasMany(NoteTemplatePro::class, 'pro_id')
  115. ->where('is_removed', false)
  116. ->orderBy('position_index', 'asc');
  117. }
  118. public function visitTemplates() {
  119. //TODO: use visit access
  120. return VisitTemplate::where('is_active', true)->get();
  121. }
  122. public function currentWork() {
  123. return ProClientWork::where('pro_id', $this->id)->where('is_active', true)->first();
  124. }
  125. public function isWorkingOnClient($_client) {
  126. $count = ProClientWork::where('pro_id', $this->id)->where('client_id', $_client->id)->where('is_active', true)->count();
  127. return $count > 0;
  128. }
  129. public function canvasCustomItems($_key) {
  130. return ClientCanvasDataCustomItem::where('key', $_key)
  131. ->where('pro_id', $this->id)
  132. ->where('is_removed', false)
  133. ->orderBy('label')
  134. ->get();
  135. }
  136. /**
  137. * @param $_start - YYYY-MM-DD
  138. * @param $_end - YYYY-MM-DD
  139. * @param string $_timezone - defaults to EASTERN
  140. * @param string $_availableBG - defaults to #00a
  141. * @param string $_unavailableBG - defaults to #a00
  142. * @return array
  143. * @throws Exception
  144. */
  145. public function getAvailabilityEvents($_start, $_end, $_timezone = 'EASTERN', $_availableBG = '#00a', $_unavailableBG = '#a00') {
  146. $_start .= ' 00:00:00';
  147. $_end .= ' 23:59:59';
  148. // get availability data
  149. $proGenAvail = ProGeneralAvailability
  150. ::where('is_cancelled', false)
  151. ->where('pro_id', $this->id)
  152. ->get();
  153. $proSpecAvail = ProSpecificAvailability
  154. ::where('is_cancelled', false)
  155. ->where('pro_id', $this->id)
  156. ->where(function ($query) use ($_start, $_end) {
  157. $query
  158. ->where(function ($query2) use ($_start, $_end) {
  159. $query2
  160. ->where('start_time', '>=', $_start)
  161. ->where('start_time', '<=', $_end);
  162. })
  163. ->orWhere(function ($query2) use ($_start, $_end) {
  164. $query2
  165. ->where('end_time', '>=', $_start)
  166. ->where('end_time', '<=', $_end);
  167. });
  168. })
  169. ->get();
  170. $proSpecUnavail = ProSpecificUnavailability
  171. ::where('is_cancelled', false)
  172. ->where('pro_id', $this->id)
  173. ->where(function ($query) use ($_start, $_end) {
  174. $query
  175. ->where(function ($query2) use ($_start, $_end) {
  176. $query2
  177. ->where('start_time', '>=', $_start)
  178. ->where('start_time', '<=', $_end);
  179. })
  180. ->orWhere(function ($query2) use ($_start, $_end) {
  181. $query2
  182. ->where('end_time', '>=', $_start)
  183. ->where('end_time', '<=', $_end);
  184. });
  185. })
  186. ->get();
  187. // default GA
  188. // if no gen avail, assume mon to fri, 9 to 7
  189. /*if (count($proGenAvail) === 0) {
  190. $dayNames = ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY'];
  191. foreach ($dayNames as $dayName) {
  192. $item = new \stdClass();
  193. $item->day_of_week = $dayName;
  194. $item->timezone = $_timezone;
  195. $item->start_time = '09:00:00';
  196. $item->end_time = '18:00:00';
  197. $proGenAvail->push($item);
  198. }
  199. }*/
  200. // create timeline
  201. $phpTZ = appTZtoPHPTZ($_timezone);
  202. $phpTZObject = new \DateTimeZone($phpTZ);
  203. $startDate = new \DateTime($_start, $phpTZObject);
  204. $endDate = new \DateTime($_end, $phpTZObject);
  205. $proTimeLine = new TimeLine($startDate, $endDate);
  206. // General availability
  207. $period = new \DatePeriod($startDate, \DateInterval::createFromDateString('1 day'), $endDate);
  208. $days = [];
  209. foreach ($period as $day) {
  210. $days[] = [
  211. "day" => strtoupper($day->format("l")), // SUNDAY, etc.
  212. "date" => $day->format("Y-m-d"), // 2020-10-04, etc.
  213. ];
  214. }
  215. foreach ($days as $day) {
  216. $proGenAvailForTheDay = $proGenAvail->filter(function ($record) use ($day) {
  217. return $record->day_of_week === $day["day"];
  218. });
  219. foreach ($proGenAvailForTheDay as $ga) {
  220. $gaStart = new \DateTime($day["date"], new \DateTimeZone(appTZtoPHPTZ($ga->timezone)));
  221. $parts = explode(":", $ga->start_time);
  222. $gaStart->setTime(intval($parts[0]), intval($parts[1]), intval($parts[2]));
  223. $gaStart->setTimezone($phpTZObject);
  224. $gaEnd = new \DateTime($day["date"], new \DateTimeZone(appTZtoPHPTZ($ga->timezone)));
  225. $parts = explode(":", $ga->end_time);
  226. $gaEnd->setTime(intval($parts[0]), intval($parts[1]), intval($parts[2]));
  227. $gaEnd->setTimezone($phpTZObject);
  228. $proTimeLine->addAvailability($gaStart, $gaEnd);
  229. }
  230. }
  231. // specific availability
  232. foreach ($proSpecAvail as $sa) {
  233. $saStart = new \DateTime($sa->start_time, new \DateTimeZone(appTZtoPHPTZ($sa->timezone)));
  234. $saStart->setTimezone($phpTZObject);
  235. $saEnd = new \DateTime($sa->end_time, new \DateTimeZone(appTZtoPHPTZ($sa->timezone)));
  236. $saEnd->setTimezone($phpTZObject);
  237. $proTimeLine->addAvailability($saStart, $saEnd);
  238. }
  239. // specific unavailability
  240. foreach ($proSpecUnavail as $sua) {
  241. $suaStart = new \DateTime($sua->start_time, new \DateTimeZone(appTZtoPHPTZ($sua->timezone)));
  242. $suaStart->setTimezone($phpTZObject);
  243. $suaEnd = new \DateTime($sua->end_time, new \DateTimeZone(appTZtoPHPTZ($sua->timezone)));
  244. $suaEnd->setTimezone($phpTZObject);
  245. $proTimeLine->removeAvailability($suaStart, $suaEnd);
  246. }
  247. $events = [];
  248. // availability
  249. foreach ($proTimeLine->getAvailable() as $item) {
  250. $eStart = new \DateTime('@' . $item->start);
  251. $eStart->setTimezone($phpTZObject);
  252. $eEnd = new \DateTime('@' . $item->end);
  253. $eEnd->setTimezone($phpTZObject);
  254. $events[] = [
  255. "type" => "availability",
  256. "start" => $eStart->format('Y-m-d H:i:s'),
  257. "end" => $eEnd->format('Y-m-d H:i:s'),
  258. "editable" => false,
  259. "backgroundColor" => $_availableBG
  260. ];
  261. }
  262. // unavailability
  263. foreach ($proTimeLine->getUnavailable() as $item) {
  264. $eStart = new \DateTime('@' . $item->start);
  265. $eStart->setTimezone($phpTZObject);
  266. $eEnd = new \DateTime('@' . $item->end);
  267. $eEnd->setTimezone($phpTZObject);
  268. $events[] = [
  269. "type" => "unavailability",
  270. "start" => $eStart->format('Y-m-d H:i:s'),
  271. "end" => $eEnd->format('Y-m-d H:i:s'),
  272. "editable" => false,
  273. "backgroundColor" => $_unavailableBG
  274. ];
  275. }
  276. return $events;
  277. }
  278. public function getMyClientIds($_search = false) {
  279. $clients = $this->getAccessibleClientsQuery($_search)->get();
  280. $clientIds = [];
  281. foreach($clients as $client){
  282. $clientIds[] = $client->id;
  283. }
  284. return $clientIds;
  285. }
  286. public function favoritesByCategory($_category) {
  287. return ProFavorite::where('pro_id', $this->id)
  288. ->where('is_removed', false)
  289. ->where('category', $_category)
  290. ->orderBy('category', 'asc')
  291. ->orderBy('position_index', 'asc')
  292. ->get();
  293. }
  294. public function favoritesByCategoryDecoded($_category) {
  295. $favorites = ProFavorite::where('pro_id', $this->id)
  296. ->where('is_removed', false)
  297. ->where('category', $_category)
  298. ->orderBy('category', 'asc')
  299. ->orderBy('position_index', 'asc')
  300. ->get();
  301. foreach ($favorites as $favorite) {
  302. if ($favorite->data) {
  303. $favorite->data = json_decode($favorite->data);
  304. }
  305. }
  306. return $favorites;
  307. }
  308. function get_patients_count_as_mcp() {
  309. $query = Client::whereNull('shadow_pro_id');
  310. return $query->where('mcp_pro_id', $this->id)->count();
  311. }
  312. function get_new_patients_awaiting_visit_count_as_mcp() {
  313. $query = Client::whereNull('shadow_pro_id');
  314. return $query->where('mcp_pro_id', $this->id)
  315. ->where('has_mcp_done_onboarding_visit', '!=', 'YES')
  316. ->count();
  317. }
  318. function get_notes_pending_signature_count_as_mcp() {
  319. return Note::where('hcp_pro_id', $this->id)
  320. ->where('is_cancelled', '<>', true)
  321. ->where('is_core_note', '<>', true)
  322. ->where('is_signed_by_hcp', '<>', true)
  323. ->count();
  324. }
  325. function get_notes_pending_summary_suggestion_as_mcp_query(){
  326. $segmentsWithProposedSummarySuggestion = Segment::whereHas('proposedSegmentSummarySuggestion', function($sugQuery){
  327. return $sugQuery->where('status', '=', 'PENDING');
  328. })->get();
  329. $noteIDs = [];
  330. foreach($segmentsWithProposedSummarySuggestion as $seg){
  331. $noteIDs[] = $seg->note_id;
  332. }
  333. return Note::where('hcp_pro_id', $this->id)
  334. ->where('is_cancelled', '<>', true)
  335. ->where('is_core_note', '<>', true)
  336. ->where('is_signed_by_hcp', true)
  337. ->whereIn('id', $noteIDs);
  338. }
  339. function get_notes_rejected_summary_suggestion_as_mcp_query(){
  340. $segmentsWithProposedSummarySuggestion = Segment::whereHas('proposedSegmentSummarySuggestion', function($sugQuery){
  341. return $sugQuery->where('status', '=', 'REJECTED');
  342. })->get();
  343. $noteIDs = [];
  344. foreach($segmentsWithProposedSummarySuggestion as $seg){
  345. $noteIDs[] = $seg->note_id;
  346. }
  347. return Note::where('hcp_pro_id', $this->id)
  348. ->where('is_cancelled', '<>', true)
  349. ->where('is_core_note', '<>', true)
  350. ->where('is_signed_by_hcp', true)
  351. ->whereIn('id', $noteIDs);
  352. }
  353. function get_notes_pending_summary_suggestion_count_as_mcp(){
  354. return $this->get_notes_pending_summary_suggestion_as_mcp_query()->count();
  355. }
  356. function get_notes_pending_summary_suggestion_as_mcp(){
  357. return $this->get_notes_pending_summary_suggestion_as_mcp_query()->get();
  358. }
  359. function get_notes_rejected_summary_suggestion_count_as_mcp(){
  360. return $this->get_notes_rejected_summary_suggestion_as_mcp_query()->count();
  361. }
  362. function get_notes_rejected_summary_suggestion_as_mcp(){
  363. return $this->get_notes_rejected_summary_suggestion_as_mcp_query()->get();
  364. }
  365. function get_notes_pending_summary_suggestion_as_admin_query(){
  366. $segmentsWithProposedSummarySuggestion = Segment::whereHas('proposedSegmentSummarySuggestion', function($sugQuery){
  367. return $sugQuery->where('status', '=', 'PENDING');
  368. })->get();
  369. $noteIDs = [];
  370. foreach($segmentsWithProposedSummarySuggestion as $seg){
  371. $noteIDs[] = $seg->note_id;
  372. }
  373. return Note::where('is_cancelled', '<>', true)
  374. ->where('is_core_note', '<>', true)
  375. ->where('is_signed_by_hcp', true)
  376. ->whereIn('id', $noteIDs);
  377. }
  378. function get_notes_rejected_summary_suggestion_as_admin_query(){
  379. $segmentsWithProposedSummarySuggestion = Segment::whereHas('proposedSegmentSummarySuggestion', function($sugQuery){
  380. return $sugQuery->where('status', '=', 'REJECTED');
  381. })->get();
  382. $noteIDs = [];
  383. foreach($segmentsWithProposedSummarySuggestion as $seg){
  384. $noteIDs[] = $seg->note_id;
  385. }
  386. return Note::where('is_cancelled', '<>', true)
  387. ->where('is_core_note', '<>', true)
  388. ->where('is_signed_by_hcp', true)
  389. ->whereIn('id', $noteIDs);
  390. }
  391. function get_notes_pending_summary_suggestion_count_as_admin(){
  392. return $this->get_notes_pending_summary_suggestion_as_admin_query()->count();
  393. }
  394. function get_notes_pending_summary_suggestion_as_admin(){
  395. return $this->get_notes_pending_summary_suggestion_as_admin_query()->get();
  396. }
  397. function get_notes_rejected_summary_suggestion_count_as_admin(){
  398. return $this->get_notes_rejected_summary_suggestion_as_admin_query()->count();
  399. }
  400. function get_notes_rejected_summary_suggestion_as_admin(){
  401. return $this->get_notes_rejected_summary_suggestion_as_admin_query()->get();
  402. }
  403. function get_notes_pending_billing_count_as_mcp() {
  404. return Note::where('hcp_pro_id', $this->id)
  405. ->where('is_cancelled', '<>', true)
  406. ->where('is_signed_by_hcp', true)
  407. ->where('is_billing_marked_done', '<>', true)
  408. ->count();
  409. }
  410. function get_measurements_awaiting_review_count_as_mcp() {
  411. $result = DB::select(DB::raw("
  412. SELECT SUM(rm_num_measurements_not_stamped_by_mcp) AS count
  413. FROM care_month
  414. WHERE mcp_pro_id = :pro_id
  415. AND rm_num_measurements_not_stamped_by_mcp IS NOT NULL
  416. AND rm_num_measurements_not_stamped_by_mcp > 0;
  417. "), ["pro_id" => $this->id]);
  418. if($result) return $result[0]->count;
  419. }
  420. function get_bills_pending_signature_count_as_mcp(){
  421. $pendingBillsToSign = Bill::where('bill_service_type', '<>', 'CARE_MONTH')->where(function ($query) {
  422. $query->where('hcp_pro_id', $this->id)->where('is_signed_by_hcp', false)->where('is_cancelled', false);
  423. })
  424. ->orWhere(function ($query) {
  425. $query->where('cm_pro_id', $this->id)->where('is_signed_by_cm', false)->where('is_cancelled', false);
  426. })->orWhere(function ($query) {
  427. $query->where('rme_pro_id', $this->id)->where('is_signed_by_rme', false)->where('is_cancelled', false);
  428. })->orWhere(function ($query) {
  429. $query->where('rmm_pro_id', $this->id)->where('is_signed_by_rmm', false)->where('is_cancelled', false);
  430. })->orWhere(function ($query) {
  431. $query->where('generic_pro_id', $this->id)->where('is_signed_by_generic_pro', false)->where('is_cancelled', false);
  432. })->count();
  433. return $pendingBillsToSign;
  434. }
  435. function get_incoming_reports_pending_signature_count_as_mcp() {
  436. return IncomingReport::where('hcp_pro_id', $this->id)
  437. ->where('has_hcp_pro_signed', '<>', true)
  438. ->where('is_entry_error', '<>', true)
  439. ->count();
  440. }
  441. function get_patients_without_appointment_query() {
  442. return Client::where('mcp_pro_id', $this->id)
  443. ->whereNull('today_mcp_appointment_date')
  444. ->where(function($q){
  445. $q->whereNull('next_mcp_appointment_id')
  446. ->orWhere('next_mcp_appointment_date', '<=', DB::raw('NOW()::DATE'));
  447. });
  448. }
  449. function get_patients_without_appointment_for_dna_query() {
  450. return Client::where('default_na_pro_id', $this->id)
  451. ->whereNull('today_mcp_appointment_date')
  452. ->where(function($q){
  453. $q->whereNull('next_mcp_appointment_id')
  454. ->orWhere('next_mcp_appointment_date', '<=', DB::raw('NOW()::DATE'));
  455. });
  456. }
  457. function get_patients_without_appointment_count_as_mcp() {
  458. return $this->get_patients_without_appointment_query()->count();
  459. }
  460. function get_patients_overdue_for_visit_query() {
  461. return Client::where('mcp_pro_id', $this->id)
  462. ->where(function($q){
  463. $q->whereNull('most_recent_completed_mcp_note_id')
  464. ->orWhere('most_recent_completed_mcp_note_date', '<', DB::raw("NOW()::DATE - INTERVAL '45 DAY'"));
  465. });
  466. }
  467. function get_patients_overdue_for_visit_for_dna_query() {
  468. return Client::where('default_na_pro_id', $this->id)
  469. ->where(function($q){
  470. $q->whereNull('most_recent_completed_mcp_note_id')
  471. ->orWhere('most_recent_completed_mcp_note_date', '<', DB::raw("NOW()::DATE - INTERVAL '45 DAY'"));
  472. });
  473. }
  474. function get_patients_overdue_count_as_mcp() {
  475. return $this->get_patients_overdue_for_visit_query()->count();
  476. }
  477. function get_patients_without_remote_measurement_in_48_hours_count_as_mcp() {
  478. return DB::select("SELECT COUNT(*) as count FROM client WHERE ((most_recent_cellular_measurement_at+ interval '48 hour')::timestamp < NOW() OR most_recent_cellular_measurement_id IS NULL) AND client.mcp_pro_id = :mcp_pro_id AND is_active IS TRUE", ['mcp_pro_id'=>$this->id])[0]->count;
  479. }
  480. function get_cancelled_appointments_pending_acknowledgement_count_as_mcp_query() {
  481. // SELECT * FROM appointment WHERE hcp_pro_id = :me.id AND status = 'REJECTED' AND wasAcknowledgedByAppointmentPro IS NOT TRUE;
  482. return Appointment::where('pro_id', $this->id)
  483. ->where('latest_confirmation_decision_enum', 'REJECTED')
  484. ->where('is_decision_acknowledgement_from_appointment_pro_pending', true);
  485. }
  486. function get_cancelled_appointments_pending_acknowledgement_count_as_mcp() {
  487. // SELECT * FROM appointment WHERE hcp_pro_id = :me.id AND status = 'REJECTED' AND wasAcknowledgedByAppointmentPro IS NOT TRUE;
  488. return $this->get_cancelled_appointments_pending_acknowledgement_count_as_mcp_query()->count();
  489. }
  490. function get_cancelled_bills_awaiting_review_count_as_mcp() {
  491. // SELECT * FROM bill WHERE bill_service_type = 'NOTE' AND is_cancelled IS TRUE AND isCancellationAcknowledged IS FALSE;
  492. return Bill::where('hcp_pro_id', $this->id)
  493. ->where('bill_service_type', 'NOTE')
  494. ->where('is_cancelled', true)
  495. ->where('is_cancellation_acknowledged', '<>', true)
  496. ->count();
  497. }
  498. function get_cancelled_supply_orders_awaiting_review_count_as_mcp() {
  499. // SELECT * FROM supply_order WHERE signed_by_pro_id = :me.id AND is_cancelled IS TRUE AND isCancellationAcknowledged IS NOT TRUE;
  500. return SupplyOrder::where('signed_by_pro_id', $this->id)
  501. ->where('is_cancelled', true)
  502. ->where('is_cancellation_acknowledged', '<>', true)
  503. ->count();
  504. }
  505. function get_erx_and_orders_awaiting_signature_count_as_mcp() {
  506. // SELECT * FROM erx WHERE hcp_pro_id = :me.id AND pro_declared_status <> 'CANCELLED' AND hasHcpProSigned IS NOT TRUE;
  507. return Erx::where('hcp_pro_id', $this->id)
  508. ->where('pro_declared_status', '<>', 'CANCELLED')
  509. ->where('has_hcp_pro_signed', '<>', true)
  510. ->count();
  511. }
  512. function get_supply_orders_awaiting_signature_count_as_mcp() {
  513. // SELECT supply_order.id FROM supply_order WHERE signed_by_pro_id IS NOT TRUE AND is_cancelled IS NOT TRUE AND created_by_pro_id = :me.id;
  514. return SupplyOrder::where('created_by_pro_id', $this->id)
  515. ->whereNull('signed_by_pro_id')
  516. ->where('is_cancelled', '<>', true)
  517. ->count();
  518. }
  519. function get_supply_orders_awaiting_shipment_count_as_mcp() {
  520. return SupplyOrder::where('created_by_pro_id', $this->id)
  521. ->where('is_signed_by_pro', true)
  522. ->where('is_cleared_for_shipment', true)
  523. ->whereNull('shipment_id')
  524. ->count();
  525. }
  526. function get_birthdays_today_as_mcp(){
  527. return;
  528. $queryClients = $this->performer()->pro->getAccessibleClientsQuery();
  529. $keyNumbers['patientsHavingBirthdayToday'] = $queryClients
  530. ->whereRaw('EXTRACT(DAY from dob) = ?', [date('d')])
  531. ->whereRaw('EXTRACT(MONTH from dob) = ?', [date('m')])
  532. ->count();
  533. $reimbursement = [];
  534. $reimbursement["currentBalance"] = $performer->pro->balance;
  535. $reimbursement["nextPaymentDate"] = '--';
  536. $lastPayment = ProTransaction::where('pro_id', $performerProID)->where('plus_or_minus', 'PLUS')->orderBy('created_at', 'DESC')->first();
  537. if ($lastPayment) {
  538. $reimbursement["lastPayment"] = $lastPayment->amount;
  539. $reimbursement["lastPaymentDate"] = $lastPayment->created_at;
  540. } else {
  541. $reimbursement["lastPayment"] = '--';
  542. $reimbursement["lastPaymentDate"] = '--';
  543. }
  544. }
  545. public function getAppointmentsPendingStatusChangeAck() {
  546. return Appointment::where('pro_id', $this->id)
  547. ->where('is_status_acknowledgement_from_appointment_pro_pending', true)
  548. //->where('raw_date', '>=', DB::raw('NOW()'))
  549. ->orderBy('raw_date', 'asc')
  550. ->get();
  551. }
  552. public function getAppointmentsPendingDecisionAck() {
  553. return Appointment::where('pro_id', $this->id)
  554. ->where('is_decision_acknowledgement_from_appointment_pro_pending', true)
  555. //->where('raw_date', '>=', DB::raw('NOW()'))
  556. ->orderBy('raw_date', 'asc')
  557. ->get();
  558. }
  559. public function getAppointmentsPendingTimeChangeAck() {
  560. return Appointment::where('pro_id', $this->id)
  561. ->where('is_time_change_acknowledgement_from_appointment_pro_pending', true)
  562. //->where('raw_date', '>=', DB::raw('NOW()'))
  563. ->orderBy('raw_date', 'asc')
  564. ->get();
  565. }
  566. public function getAccessibleClientsQuery($_search = false) {
  567. $proID = $this->id;
  568. $query = Client::whereNull('shadow_pro_id');
  569. if ($this->pro_type === 'ADMIN' && ($_search ? $this->can_see_any_client_via_search : $this->can_see_all_clients_in_list)) {
  570. $query = $query->where('id', '>', 0);
  571. } else {
  572. $query = $query->where(function ($q) use ($proID) {
  573. $q->where('mcp_pro_id', $proID)
  574. ->orWhere('cm_pro_id', $proID)
  575. ->orWhere('rmm_pro_id', $proID)
  576. ->orWhere('rme_pro_id', $proID)
  577. ->orWhere('physician_pro_id', $proID)
  578. ->orWhere('default_na_pro_id', $proID)
  579. ->orWhereRaw('id IN (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = ?)', [$proID])
  580. ->orWhereRaw('id IN (SELECT client_id FROM appointment WHERE status NOT IN (\'CANCELLED\') AND pro_id = ?)', [$proID])
  581. ->orWhereRaw('id IN (SELECT mcp_pro_id FROM client_program WHERE client_id = client.id AND is_active = TRUE)')
  582. ->orWhereRaw('id IN (SELECT manager_pro_id FROM client_program WHERE client_id = client.id AND is_active = TRUE)')
  583. ->orWhereRaw('id IN (SELECT client_id FROM note WHERE ally_pro_id = ? AND is_cancelled = FALSE)', [$proID]);;
  584. });
  585. }
  586. return $query;
  587. }
  588. public function canAccess($_patientUid) {
  589. $proID = $this->id;
  590. if ($this->pro_type === 'ADMIN') {
  591. return true;
  592. }
  593. $canAccess = Client::select('uid')
  594. ->where('uid', $_patientUid)
  595. ->where(function ($q) use ($proID) {
  596. $q->whereNull('mcp_pro_id')
  597. ->orWhere('mcp_pro_id', $proID)
  598. ->orWhere('cm_pro_id', $proID)
  599. ->orWhere('rmm_pro_id', $proID)
  600. ->orWhere('rme_pro_id', $proID)
  601. ->orWhere('physician_pro_id', $proID)
  602. ->orWhere('default_na_pro_id', $proID)
  603. ->orWhereRaw('id IN (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = ?)', [$proID])
  604. ->orWhereRaw('id IN (SELECT client_id FROM appointment WHERE status NOT IN (\'CANCELLED\') AND pro_id = ?)', [$proID])
  605. ->orWhereRaw('id IN (SELECT mcp_pro_id FROM client_program WHERE client_id = client.id AND is_active = TRUE)')
  606. ->orWhereRaw('id IN (SELECT manager_pro_id FROM client_program WHERE client_id = client.id AND is_active = TRUE)')
  607. ->orWhereRaw('id IN (SELECT client_id FROM note WHERE ally_pro_id = ? AND is_cancelled = FALSE)', [$proID]);
  608. })->count();
  609. return !!$canAccess;
  610. }
  611. public function canAddCPMEntryForMeasurement(Measurement $measurement, Pro $pro)
  612. {
  613. // check if client has any programs where this measurement type is allowed
  614. $allowed = false;
  615. $client = $measurement->client;
  616. $clientPrograms = $client->clientPrograms;
  617. if($pro->pro_type !== 'ADMIN') {
  618. $clientPrograms = $clientPrograms->filter(function($_clientProgram) use ($pro) {
  619. return $_clientProgram->manager_pro_id === $pro->id;
  620. });
  621. }
  622. if(count($clientPrograms)) {
  623. foreach ($clientPrograms as $clientProgram) {
  624. if(strpos(strtolower($clientProgram->measurement_labels), '|' . strtolower($measurement->label) . '|') !== FALSE) {
  625. $allowed = true;
  626. break;
  627. }
  628. }
  629. }
  630. return $allowed ? $clientPrograms : FALSE;
  631. }
  632. public function getUnstampedMeasurementsFromCurrentMonth($_countOnly, $skip, $limit)
  633. {
  634. date_default_timezone_set('US/Eastern');
  635. $start = strtotime(date('Y-m-01'));
  636. $end = date_add(date_create(date('Y-m-01')), date_interval_create_from_date_string("1 month"))->getTimestamp();
  637. $start *= 1000;
  638. $end *= 1000;
  639. $measurementsQuery = Measurement::where('measurement.is_active', true)
  640. ->join('client', 'client.id', '=', 'measurement.client_id')
  641. ->whereNotNull('measurement.client_bdt_measurement_id')
  642. ->whereNotNull('measurement.ts')
  643. ->where('measurement.is_cellular_zero', false)
  644. ->where('measurement.ts', '>=', $start)
  645. ->where('measurement.ts', '<', $end)
  646. ->whereIn('measurement.client_id', $this->getMyClientIds())
  647. ->where(function ($q) {
  648. $q
  649. ->where(function ($q2) {
  650. $q2
  651. ->where('client.mcp_pro_id', $this->id)
  652. ->where('measurement.has_been_stamped_by_mcp', false);
  653. })
  654. ->orWhere(function ($q2) {
  655. $q2
  656. ->where('client.default_na_pro_id', $this->id)
  657. ->where('measurement.has_been_stamped_by_non_hcp', false);
  658. })
  659. ->orWhere(function ($q2) {
  660. $q2
  661. ->where('client.rmm_pro_id', $this->id)
  662. ->where('measurement.has_been_stamped_by_rmm', false);
  663. })
  664. ->orWhere(function ($q2) {
  665. $q2
  666. ->where('client.rme_pro_id', $this->id)
  667. ->where('measurement.has_been_stamped_by_rme', false);
  668. });
  669. });
  670. if($_countOnly) {
  671. return $measurementsQuery->count();
  672. }
  673. $x = [];
  674. $measurements = $measurementsQuery
  675. ->orderBy('ts', 'desc')
  676. ->skip($skip)
  677. ->take($limit)
  678. ->get();
  679. // eager load stuff needed in JS
  680. foreach ($measurements as $measurement) {
  681. // if ($measurement->client_bdt_measurement_id) {
  682. // $measurement->bdtMeasurement = $measurement->clientBDTMeasurement->measurement;
  683. // }
  684. unset($measurement->clientBDTMeasurement); // we do not need this travelling to the frontend
  685. $client = [
  686. "uid" => $measurement->client->uid,
  687. "name" => $measurement->client->displayName(),
  688. ];
  689. $measurement->patient = $client;
  690. $measurement->careMonth = $measurement->client->currentCareMonth();
  691. $measurement->timestamp = friendlier_date_time($measurement->created_at);
  692. unset($measurement->client); // we do not need this travelling to the frontend
  693. if(@$measurement->detail_json) unset($measurement->detail_json);
  694. if(@$measurement->canvas_data) unset($measurement->canvas_data);
  695. if(@$measurement->latest_measurements) unset($measurement->latest_measurements);
  696. if(@$measurement->info_lines) unset($measurement->info_lines);
  697. if(@$measurement->canvas_data_backup) unset($measurement->canvas_data_backup);
  698. if(@$measurement->migrated_canvas_data_backup) unset($measurement->migrated_canvas_data_backup);
  699. // if($measurement->label == 'SBP' || $measurement->label = 'DBP'){
  700. // continue;
  701. // }
  702. $x[] = $measurement;
  703. }
  704. // dd($measurements);
  705. return $measurements;
  706. }
  707. public function getMeasurements($_onlyUnstamped = true)
  708. {
  709. $measurementsQuery = Measurement::where('is_removed', false);
  710. if ($this->pro_type != 'ADMIN') {
  711. $measurementsQuery
  712. ->whereIn('client_id', $this->getMyClientIds());
  713. }
  714. if ($_onlyUnstamped) {
  715. $measurementsQuery
  716. ->whereNotNull('client_bdt_measurement_id')
  717. ->whereNotNull('ts')
  718. ->where('is_cellular_zero', false)
  719. ->where(function ($q) {
  720. $q->whereNull('status')
  721. ->orWhere(function ($q2) {
  722. $q2->where('status', '<>', 'ACK')
  723. ->where('status', '<>', 'INVALID_ACK');
  724. });
  725. });
  726. }
  727. $x = [];
  728. $measurements = $measurementsQuery->orderBy('ts', 'desc')->paginate(50);
  729. // eager load stuff needed in JS
  730. foreach ($measurements as $measurement) {
  731. // if ($measurement->client_bdt_measurement_id) {
  732. // $measurement->bdtMeasurement = $measurement->clientBDTMeasurement->measurement;
  733. // }
  734. unset($measurement->clientBDTMeasurement); // we do not need this travelling to the frontend
  735. $client = [
  736. "uid" => $measurement->client->uid,
  737. "name" => $measurement->client->displayName(),
  738. ];
  739. $measurement->patient = $client;
  740. $measurement->careMonth = $measurement->client->currentCareMonth();
  741. $measurement->timestamp = friendly_date_time($measurement->created_at);
  742. unset($measurement->client); // we do not need this travelling to the frontend
  743. // if($measurement->label == 'SBP' || $measurement->label = 'DBP'){
  744. // continue;
  745. // }
  746. $x[] = $measurement;
  747. }
  748. return $measurements;
  749. }
  750. public function companyPros()
  751. {
  752. return $this->hasMany(CompanyPro::class, 'pro_id', 'id')
  753. ->where('is_active', true);
  754. }
  755. public function companyProPayers()
  756. {
  757. return $this->hasMany(CompanyProPayer::class, 'pro_id', 'id');
  758. }
  759. public function isAssociatedWithMCPayer() {
  760. $companyProPayers = $this->companyProPayers;
  761. $foundMC = false;
  762. if($companyProPayers) {
  763. foreach ($companyProPayers as $companyProPayer) {
  764. if($companyProPayer->payer && $companyProPayer->payer->is_medicare) {
  765. $foundMC = true;
  766. break;
  767. }
  768. }
  769. }
  770. return $foundMC;
  771. }
  772. public function isAssociatedWithNonMCPayer($_payerID) {
  773. $companyProPayers = $this->companyProPayers;
  774. $foundNonMC = false;
  775. if($companyProPayers) {
  776. foreach ($companyProPayers as $companyProPayer) {
  777. if($companyProPayer->payer && !$companyProPayer->payer->is_medicare && $companyProPayer->payer->id === $_payerID) {
  778. $foundNonMC = true;
  779. break;
  780. }
  781. }
  782. }
  783. return $foundNonMC;
  784. }
  785. public function companyLocations() {
  786. $companyProPayers = $this->companyProPayers;
  787. $companyIDs = [];
  788. foreach ($companyProPayers as $companyProPayer) {
  789. $companyIDs[] = $companyProPayer->company_id;
  790. }
  791. $locations = [];
  792. if(count($companyIDs)) {
  793. $locations = CompanyLocation::whereIn('id', $companyIDs)->get();
  794. }
  795. return $locations;
  796. }
  797. public function shadowClient() {
  798. return $this->hasOne(Client::class, 'id', 'shadow_client_id');
  799. }
  800. public function defaultCompanyPro() {
  801. return $this->hasOne(CompanyPro::class, 'id', 'default_company_pro_id');
  802. }
  803. public function currentNotePickupForProcessing() {
  804. return $this->hasOne(NotePickupForProcessing::class, 'id', 'current_note_pickup_for_processing_id');
  805. }
  806. public function get_patients_not_seen_in_45_days_count_as_mcp(){
  807. return 0;
  808. }
  809. //DNA_DASHBOARD
  810. //queries
  811. private function patientsQueryAsDna(){
  812. // WHERE na_pro_id = :me.id
  813. return Client::where('default_na_pro_id', $this->id);
  814. }
  815. private function patientsAwaitingMcpVisitQueryAsDna(){
  816. // WHERE has_mcp_done_onboarding_visit <> 'YES'
  817. return Client::where('default_na_pro_id', $this->id)->where('has_mcp_done_onboarding_visit', '<>', 'YES');
  818. }
  819. private function patientsWithoutAppointmentQueryAsDna(){
  820. // WHERE today_mcp_appointment_date IS NULL AND next_mcp_appointment_date IS NULL
  821. return Client::where('default_na_pro_id', $this->id)
  822. ->whereNull('today_mcp_appointment_date')
  823. ->whereNull('next_mcp_appointment_date');
  824. }
  825. private function encountersPendingMyReviewQueryAsDna(){
  826. // WHERE ally_pro_id = me.id AND is_cancelled IS NOT TRUE AND is_signed_by_hcp IS TRUE AND is_signed_by_ally IS NOT TRUE;
  827. return Note::where('ally_pro_id', $this->id)
  828. ->where('is_cancelled', '<>', true)
  829. ->where('is_signed_by_hcp', true)
  830. ->where('is_signed_by_ally','<>', true);
  831. }
  832. private function encountersInProgressQueryAsDna(){
  833. // SELECT * FROM note WHERE ally_pro_id = me.id AND is_cancelled IS NOT TRUE AND is_signed_by_hcp IS NOT TRUE ORDER BY effective_dateest DESC, created_at DESC;
  834. return Note::where('ally_pro_id', $this->id)
  835. ->where('is_cancelled', '<>', true)
  836. ->where('is_signed_by_hcp', '<>', true);
  837. }
  838. private function appointmentsPendingConfirmationQueryAsDna(){
  839. // WHERE client_id IN (SELECT id FROM client WHERE default_na_pro_id = :me.id) AND status = 'PENDING'
  840. $myId = $this->id;
  841. return Appointment::whereHas('client', function($clientQuery) use ($myId) {
  842. return $clientQuery->where('default_na_pro_id', $myId);
  843. })->where('status', 'PENDING');
  844. }
  845. private function cancelledAppointmentsPendingAckQueryAsDna(){
  846. // WHERE client_id IN (SELECT id FROM client WHERE default_na_pro_id = :me.id) AND status = 'CANCELLED' AND is_status_acknowledgement_from_default_na_pending IS TRUE;
  847. $myId = $this->id;
  848. return Appointment::whereHas('client', function($clientQuery) use ($myId) {
  849. return $clientQuery->where('default_na_pro_id', $myId);
  850. })->where('status', 'CANCELLED')
  851. ->where('is_status_acknowledgement_from_default_na_pending', true);
  852. }
  853. private function reportsPendingAckQueryAsDna(){
  854. // WHERE client_id IN (SELECT id FROM client WHERE default_na_pro_id = :me.id) AND has_na_pro_signed IS FALSE AND is_entry_error
  855. $myId = $this->id;
  856. return IncomingReport::whereHas('client',function($clientQuery) use ($myId) {
  857. return $clientQuery->where('default_na_pro_id', $myId);
  858. })->where('has_na_pro_signed', '<>', true)
  859. ->where('is_entry_error','<>', true);
  860. }
  861. private function supplyOrdersPendingMyAckQueryAsDna(){
  862. // WHERE client_id IN (SELECT id FROM client WHERE default_na_pro_id = :me.id) AND has_na_pro_signed IS FALSE AND is_signed_by_pro IS TRUE AND is_cancelled IS NOT TRUE;
  863. $myId = $this->id;
  864. return SupplyOrder::whereHas('client',function($clientQuery) use ($myId) {
  865. return $clientQuery->where('default_na_pro_id', $myId);
  866. })->where('has_na_pro_signed', '<>', true)
  867. ->where('is_signed_by_pro', true)
  868. ->where('is_cancelled', '<>', true);
  869. }
  870. private function supplyOrdersPendingHcpApprovalQueryAsDna(){
  871. // WHERE client_id IN (SELECT id FROM client WHERE default_na_pro_id = :me.id) AND has_na_pro_signed IS TRUE AND is_signed_by_pro IS NOT TRUE AND is_cancelled IS NOT TRUE;
  872. $myId = $this->id;
  873. return SupplyOrder::whereHas('client',function($clientQuery) use ($myId) {
  874. return $clientQuery->where('default_na_pro_id', $myId);
  875. })->where('has_na_pro_signed', true)
  876. ->where('is_signed_by_pro','<>', true)
  877. ->where('is_cancelled', '<>', true);
  878. }
  879. //counts
  880. public function patientsCountAsDna(){
  881. return $this->patientsQueryAsDna()->count();
  882. }
  883. public function patientsAwaitingMcpVisitCountAsDna(){
  884. return $this->patientsAwaitingMcpVisitQueryAsDna()->count();
  885. }
  886. public function patientsWithoutAppointmentCountAsDna(){
  887. return $this->patientsWithoutAppointmentQueryAsDna()->count();
  888. }
  889. public function encountersPendingMyReviewCountAsDna(){
  890. return $this->encountersPendingMyReviewQueryAsDna()->count();
  891. }
  892. public function encountersInProgressCountAsDna(){
  893. return $this->encountersInProgressQueryAsDna()->count();
  894. }
  895. public function appointmentsPendingConfirmationCountAsDna(){
  896. return $this->appointmentsPendingConfirmationQueryAsDna()->count();
  897. }
  898. public function cancelledAppointmentsPendingAckCountAsDna(){
  899. return $this->cancelledAppointmentsPendingAckQueryAsDna()->count();
  900. }
  901. public function reportsPendingAckCountAsDna(){
  902. return $this->reportsPendingAckQueryAsDna()->count();
  903. }
  904. public function supplyOrdersPendingMyAckCountAsDna(){
  905. return $this->supplyOrdersPendingMyAckQueryAsDna()->count();
  906. }
  907. public function supplyOrdersPendingHcpApprovalCountAsDna(){
  908. return $this->supplyOrdersPendingHcpApprovalQueryAsDna()->count();
  909. }
  910. //records
  911. private $DNA_RESULTS_PAGE_SIZE = 50;
  912. public function patientsRecordsAsDna(){
  913. return $this->patientsQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  914. }
  915. public function patientsAwaitingMcpVisitRecordsAsDna(){
  916. return $this->patientsAwaitingMcpVisitQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  917. }
  918. public function patientsWithoutAppointmentRecordsAsDna(){
  919. return $this->patientsWithoutAppointmentQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  920. }
  921. public function encountersPendingMyReviewRecordsAsDna(){
  922. return $this->encountersPendingMyReviewQueryAsDna()
  923. ->orderBy('effective_dateest', 'desc')
  924. ->orderBy('created_at', 'desc')
  925. ->paginate($this->DNA_RESULTS_PAGE_SIZE);
  926. }
  927. public function encountersInProgressRecordsAsDna(){
  928. return $this->encountersInProgressQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  929. }
  930. public function appointmentsPendingConfirmationRecordsAsDna(){
  931. return $this->appointmentsPendingConfirmationQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  932. }
  933. public function cancelledAppointmentsPendingAckRecordsAsDna(){
  934. return $this->cancelledAppointmentsPendingAckQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  935. }
  936. public function reportsPendingAckRecordsAsDna(){
  937. return $this->reportsPendingAckQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  938. }
  939. public function supplyOrdersPendingMyAckRecordsAsDna(){
  940. return $this->supplyOrdersPendingMyAckQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  941. }
  942. public function supplyOrdersPendingHcpApprovalRecordsAsDna(){
  943. return $this->supplyOrdersPendingHcpApprovalQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  944. }
  945. public function measurementsPendingReviewAsDna(){
  946. //Measurements Pending Review
  947. // SELECT * FROM measurement WHERE client_id IN (SELECT id FROM client WHERE rmm_pro_id = :me.id)
  948. // AND has_been_stamped_by_rmm IS FALSE AND is_cellular IS TRUE AND is_cellular_zero IS NOT TRUE AND is_active IS TRUE ORDER BY ts DESC;
  949. $myId = $this->id;
  950. return Measurement::whereHas('client',function($clientQuery) use ($myId) {
  951. return $clientQuery->where('rmm_pro_id', $myId);
  952. })
  953. ->where('has_been_stamped_by_rmm', '<>', true)
  954. ->where('is_cellular', true)
  955. ->where('is_cellular_zero', '<>', true)
  956. ->where('is_active', true)
  957. ->orderBy('ts', 'DESC')
  958. ->paginate(15);
  959. }
  960. public function getProcessingAmountAsDna(){
  961. $expectedForCm = DB::select(DB::raw("SELECT coalesce(SUM(cm_expected_payment_amount),0) as expected_pay FROM bill WHERE cm_pro_id = :performerProID AND has_cm_been_paid = false AND is_signed_by_cm IS TRUE AND is_cancelled = false"), ['performerProID' => $this->id])[0]->expected_pay;
  962. $expectedForRme = DB::select(DB::raw("SELECT coalesce(SUM(rme_expected_payment_amount),0) as expected_pay FROM bill WHERE rme_pro_id = :performerProID AND has_rme_been_paid = false AND is_signed_by_rme IS TRUE AND is_cancelled = false"), ['performerProID' => $this->id])[0]->expected_pay;
  963. $expectedForRmm = DB::select(DB::raw("SELECT coalesce(SUM(rmm_expected_payment_amount),0) as expected_pay FROM bill WHERE rmm_pro_id = :performerProID AND has_rmm_been_paid = false AND is_signed_by_rmm IS TRUE AND is_cancelled = false"), ['performerProID' => $this->id])[0]->expected_pay;
  964. $expectedForNa = DB::select(DB::raw("SELECT coalesce(SUM(generic_pro_expected_payment_amount),0) as expected_pay FROM bill WHERE generic_pro_id = :performerProID AND has_generic_pro_been_paid = false AND is_signed_by_generic_pro IS TRUE AND is_cancelled = false"), ['performerProID' => $this->id])[0]->expected_pay;
  965. $totalExpectedAmount = $expectedForCm + $expectedForRme + $expectedForRmm + $expectedForNa;
  966. return $totalExpectedAmount;
  967. }
  968. public function getNextPaymentDateAsDna(){
  969. $nextPaymentDate = '--';
  970. //if today is < 15th, next payment is 15th, else nextPayment is
  971. $today = strtotime(date('Y-m-d'));
  972. $todayDate = date('j', $today);
  973. $todayMonth = date('m', $today);
  974. $todayYear = date('Y', $today);
  975. if ($todayDate < 15) {
  976. $nextPaymentDate = new DateTime();
  977. $nextPaymentDate->setDate($todayYear, $todayMonth, 15);
  978. $nextPaymentDate = $nextPaymentDate->format('m/d/Y');
  979. } else {
  980. $nextPaymentDate = new \DateTime();
  981. $lastDayOfMonth = date('t', $today);
  982. $nextPaymentDate->setDate($todayYear, $todayMonth, $lastDayOfMonth);
  983. $nextPaymentDate = $nextPaymentDate->format('m/d/Y');
  984. }
  985. return $nextPaymentDate;
  986. }
  987. public function clientSmsesAsDna(){
  988. $myId = $this->id;
  989. return ClientSMS::whereHas('client', function($clientQuery) use ($myId){
  990. return $clientQuery->where('default_na_pro_id', $myId);
  991. })
  992. ->orderBy('created_at', 'DESC')
  993. ->paginate(15);
  994. }
  995. public function clientMemosAsDna(){
  996. $naClientMemos = DB::select(
  997. DB::raw("
  998. SELECT c.uid as client_uid, c.name_first, c.name_last,
  999. cm.uid, cm.content, cm.created_at
  1000. FROM client c join client_memo cm on c.id = cm.client_id
  1001. WHERE
  1002. c.default_na_pro_id = {$this->id}
  1003. ORDER BY cm.created_at DESC
  1004. ")
  1005. );
  1006. return $naClientMemos;
  1007. }
  1008. public function getAppointmentsPendingStatusChangeAckAsDna() {
  1009. $myId = $this->id;
  1010. return Appointment::whereHas('client', function($clientQuery) use ($myId){
  1011. return $clientQuery->where('default_na_pro_id', $myId);
  1012. })
  1013. ->where('is_status_acknowledgement_from_appointment_pro_pending', true)
  1014. ->where('raw_date', '>=', DB::raw('NOW()'))
  1015. ->orderBy('raw_date', 'asc')
  1016. ->get();
  1017. }
  1018. public function getAppointmentsPendingDecisionAckAsDna() {
  1019. $myId = $this->id;
  1020. return Appointment::whereHas('client', function($clientQuery) use ($myId){
  1021. return $clientQuery->where('default_na_pro_id', $myId);
  1022. })
  1023. ->where('is_decision_acknowledgement_from_appointment_pro_pending', true)
  1024. ->where('raw_date', '>=', DB::raw('NOW()'))
  1025. ->orderBy('raw_date', 'asc')
  1026. ->get();
  1027. }
  1028. public function getAppointmentsPendingTimeChangeAckAsDna() {
  1029. $myId = $this->id;
  1030. return Appointment::whereHas('client', function($clientQuery) use ($myId){
  1031. return $clientQuery->where('default_na_pro_id', $myId);
  1032. })
  1033. ->where('is_time_change_acknowledgement_from_appointment_pro_pending', true)
  1034. ->where('raw_date', '>=', DB::raw('NOW()'))
  1035. ->orderBy('raw_date', 'asc')
  1036. ->get();
  1037. }
  1038. function myGenericBills() {
  1039. return Bill::where('bill_service_type', 'GENERIC')
  1040. ->where('generic_pro_id', $this->id)
  1041. ->orderBy('created_at', 'DESC')->get();
  1042. }
  1043. public function videoHrRep() {
  1044. return $this->hasOne(Pro::class, 'id', 'video_hr_rep_pro_id');
  1045. }
  1046. public function trainingRep(){
  1047. return $this->hasOne(Pro::class, 'id', 'training_rep_pro_id');
  1048. }
  1049. public function newHrStageByPro(){
  1050. return $this->hasOne(Pro::class, 'id', 'new_hr_stage_by_pro_id');
  1051. }
  1052. public function successRep(){
  1053. return $this->hasOne(Pro::class, 'id', 'success_rep_pro_id');
  1054. }
  1055. public function offerCallRep(){
  1056. return $this->hasOne(Pro::class, 'id', 'offer_call_rep_pro_id');
  1057. }
  1058. public function previousHrStageByPro(){
  1059. return $this->hasOne(Pro::class, 'id', 'previous_hr_stage_by_pro_id');
  1060. }
  1061. public function introVideoMessage(){
  1062. return $this->hasOne(InternalMessage::class, 'id', 'intro_video_message_from_hr_rep_internal_message_id');
  1063. }
  1064. public function replyVideoMessage(){
  1065. return $this->hasOne(InternalMessage::class, 'id', 'initial_reply_to_video_hr_rep_internal_message_id');
  1066. }
  1067. public function hrSpecialist() {
  1068. return $this->hasOne(Pro::class, 'id', 'hr_rep_pro_id');
  1069. }
  1070. public function supervisingHcpPro() {
  1071. return $this->hasOne(Pro::class, 'id', 'supervising_hcp_pro_id');
  1072. }
  1073. public function clinicalSupervisor() {
  1074. return $this->hasOne(Pro::class, 'id', 'supervising_hcp_pro_id');
  1075. }
  1076. public function interviewNeededWithPro(){
  1077. return $this->hasOne(Pro::class, 'id', 'interview_needed_with_pro_id');
  1078. }
  1079. public function trainingNeededWithPro(){
  1080. return $this->hasOne(Pro::class, 'id', 'training_needed_with_pro_id');
  1081. }
  1082. public function interviewNeededWithDepertment(){
  1083. return $this->hasOne(Department::class, 'id', 'interview_needed_with_department_id');
  1084. }
  1085. public function trainingNeededWithDepartment(){
  1086. return $this->hasOne(Department::class, 'id', 'training_needed_with_department_id');
  1087. }
  1088. }