Pro.php 49 KB

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