Pro.php 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137
  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::whereNotNull('proposed_segment_summary_suggestion_id')->get();
  327. $noteIDs = [];
  328. foreach($segmentsWithProposedSummarySuggestion as $seg){
  329. $noteIDs[] = $seg->note_id;
  330. }
  331. return Note::where('hcp_pro_id', $this->id)
  332. ->where('is_cancelled', '<>', true)
  333. ->where('is_core_note', '<>', true)
  334. ->where('is_signed_by_hcp', true)
  335. ->whereIn('id', $noteIDs);
  336. }
  337. function get_notes_pending_summary_suggestion_count_as_mcp(){
  338. return $this->get_notes_pending_summary_suggestion_as_mcp_query()->count();
  339. }
  340. function get_notes_pending_summary_suggestion_as_mcp(){
  341. return $this->get_notes_pending_summary_suggestion_as_mcp_query()->get();
  342. }
  343. function get_notes_pending_summary_suggestion_as_admin_query(){
  344. $segmentsWithProposedSummarySuggestion = Segment::whereNotNull('proposed_segment_summary_suggestion_id')->get();
  345. $noteIDs = [];
  346. foreach($segmentsWithProposedSummarySuggestion as $seg){
  347. $noteIDs[] = $seg->note_id;
  348. }
  349. return Note::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_admin(){
  355. return $this->get_notes_pending_summary_suggestion_as_admin_query()->count();
  356. }
  357. function get_notes_pending_summary_suggestion_as_admin(){
  358. return $this->get_notes_pending_summary_suggestion_as_admin_query()->get();
  359. }
  360. function get_notes_pending_billing_count_as_mcp() {
  361. return Note::where('hcp_pro_id', $this->id)
  362. ->where('is_cancelled', '<>', true)
  363. ->where('is_signed_by_hcp', true)
  364. ->where('is_billing_marked_done', '<>', true)
  365. ->count();
  366. }
  367. function get_measurements_awaiting_review_count_as_mcp() {
  368. $result = DB::select(DB::raw("
  369. SELECT SUM(rm_num_measurements_not_stamped_by_mcp) AS count
  370. FROM care_month
  371. WHERE mcp_pro_id = :pro_id
  372. AND rm_num_measurements_not_stamped_by_mcp IS NOT NULL
  373. AND rm_num_measurements_not_stamped_by_mcp > 0;
  374. "), ["pro_id" => $this->id]);
  375. if($result) return $result[0]->count;
  376. }
  377. function get_bills_pending_signature_count_as_mcp(){
  378. $pendingBillsToSign = Bill::where('bill_service_type', '<>', 'CARE_MONTH')->where(function ($query) {
  379. $query->where('hcp_pro_id', $this->id)->where('is_signed_by_hcp', false)->where('is_cancelled', false);
  380. })
  381. ->orWhere(function ($query) {
  382. $query->where('cm_pro_id', $this->id)->where('is_signed_by_cm', false)->where('is_cancelled', false);
  383. })->orWhere(function ($query) {
  384. $query->where('rme_pro_id', $this->id)->where('is_signed_by_rme', false)->where('is_cancelled', false);
  385. })->orWhere(function ($query) {
  386. $query->where('rmm_pro_id', $this->id)->where('is_signed_by_rmm', false)->where('is_cancelled', false);
  387. })->orWhere(function ($query) {
  388. $query->where('generic_pro_id', $this->id)->where('is_signed_by_generic_pro', false)->where('is_cancelled', false);
  389. })->count();
  390. return $pendingBillsToSign;
  391. }
  392. function get_incoming_reports_pending_signature_count_as_mcp() {
  393. return IncomingReport::where('hcp_pro_id', $this->id)
  394. ->where('has_hcp_pro_signed', '<>', true)
  395. ->where('is_entry_error', '<>', true)
  396. ->count();
  397. }
  398. function get_patients_without_appointment_query() {
  399. return Client::where('mcp_pro_id', $this->id)
  400. ->whereNull('today_mcp_appointment_date')
  401. ->where(function($q){
  402. $q->whereNull('next_mcp_appointment_id')
  403. ->orWhere('next_mcp_appointment_date', '<=', DB::raw('NOW()::DATE'));
  404. });
  405. }
  406. function get_patients_without_appointment_for_dna_query() {
  407. return Client::where('default_na_pro_id', $this->id)
  408. ->whereNull('today_mcp_appointment_date')
  409. ->where(function($q){
  410. $q->whereNull('next_mcp_appointment_id')
  411. ->orWhere('next_mcp_appointment_date', '<=', DB::raw('NOW()::DATE'));
  412. });
  413. }
  414. function get_patients_without_appointment_count_as_mcp() {
  415. return $this->get_patients_without_appointment_query()->count();
  416. }
  417. function get_patients_overdue_for_visit_query() {
  418. return Client::where('mcp_pro_id', $this->id)
  419. ->where(function($q){
  420. $q->whereNull('most_recent_completed_mcp_note_id')
  421. ->orWhere('most_recent_completed_mcp_note_date', '<', DB::raw("NOW()::DATE - INTERVAL '45 DAY'"));
  422. });
  423. }
  424. function get_patients_overdue_for_visit_for_dna_query() {
  425. return Client::where('default_na_pro_id', $this->id)
  426. ->where(function($q){
  427. $q->whereNull('most_recent_completed_mcp_note_id')
  428. ->orWhere('most_recent_completed_mcp_note_date', '<', DB::raw("NOW()::DATE - INTERVAL '45 DAY'"));
  429. });
  430. }
  431. function get_patients_overdue_count_as_mcp() {
  432. return $this->get_patients_overdue_for_visit_query()->count();
  433. }
  434. function get_patients_without_remote_measurement_in_48_hours_count_as_mcp() {
  435. 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;
  436. }
  437. function get_cancelled_appointments_pending_acknowledgement_count_as_mcp_query() {
  438. // SELECT * FROM appointment WHERE hcp_pro_id = :me.id AND status = 'REJECTED' AND wasAcknowledgedByAppointmentPro IS NOT TRUE;
  439. return Appointment::where('pro_id', $this->id)
  440. ->where('latest_confirmation_decision_enum', 'REJECTED')
  441. ->where('is_decision_acknowledgement_from_appointment_pro_pending', true);
  442. }
  443. function get_cancelled_appointments_pending_acknowledgement_count_as_mcp() {
  444. // SELECT * FROM appointment WHERE hcp_pro_id = :me.id AND status = 'REJECTED' AND wasAcknowledgedByAppointmentPro IS NOT TRUE;
  445. return $this->get_cancelled_appointments_pending_acknowledgement_count_as_mcp_query()->count();
  446. }
  447. function get_cancelled_bills_awaiting_review_count_as_mcp() {
  448. // SELECT * FROM bill WHERE bill_service_type = 'NOTE' AND is_cancelled IS TRUE AND isCancellationAcknowledged IS FALSE;
  449. return Bill::where('hcp_pro_id', $this->id)
  450. ->where('bill_service_type', 'NOTE')
  451. ->where('is_cancelled', true)
  452. ->where('is_cancellation_acknowledged', '<>', true)
  453. ->count();
  454. }
  455. function get_cancelled_supply_orders_awaiting_review_count_as_mcp() {
  456. // SELECT * FROM supply_order WHERE signed_by_pro_id = :me.id AND is_cancelled IS TRUE AND isCancellationAcknowledged IS NOT TRUE;
  457. return SupplyOrder::where('signed_by_pro_id', $this->id)
  458. ->where('is_cancelled', true)
  459. ->where('is_cancellation_acknowledged', '<>', true)
  460. ->count();
  461. }
  462. function get_erx_and_orders_awaiting_signature_count_as_mcp() {
  463. // SELECT * FROM erx WHERE hcp_pro_id = :me.id AND pro_declared_status <> 'CANCELLED' AND hasHcpProSigned IS NOT TRUE;
  464. return Erx::where('hcp_pro_id', $this->id)
  465. ->where('pro_declared_status', '<>', 'CANCELLED')
  466. ->where('has_hcp_pro_signed', '<>', true)
  467. ->count();
  468. }
  469. function get_supply_orders_awaiting_signature_count_as_mcp() {
  470. // 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;
  471. return SupplyOrder::where('created_by_pro_id', $this->id)
  472. ->whereNull('signed_by_pro_id')
  473. ->where('is_cancelled', '<>', true)
  474. ->count();
  475. }
  476. function get_supply_orders_awaiting_shipment_count_as_mcp() {
  477. return SupplyOrder::where('created_by_pro_id', $this->id)
  478. ->where('is_signed_by_pro', true)
  479. ->where('is_cleared_for_shipment', true)
  480. ->whereNull('shipment_id')
  481. ->count();
  482. }
  483. function get_birthdays_today_as_mcp(){
  484. return;
  485. $queryClients = $this->performer()->pro->getAccessibleClientsQuery();
  486. $keyNumbers['patientsHavingBirthdayToday'] = $queryClients
  487. ->whereRaw('EXTRACT(DAY from dob) = ?', [date('d')])
  488. ->whereRaw('EXTRACT(MONTH from dob) = ?', [date('m')])
  489. ->count();
  490. $reimbursement = [];
  491. $reimbursement["currentBalance"] = $performer->pro->balance;
  492. $reimbursement["nextPaymentDate"] = '--';
  493. $lastPayment = ProTransaction::where('pro_id', $performerProID)->where('plus_or_minus', 'PLUS')->orderBy('created_at', 'DESC')->first();
  494. if ($lastPayment) {
  495. $reimbursement["lastPayment"] = $lastPayment->amount;
  496. $reimbursement["lastPaymentDate"] = $lastPayment->created_at;
  497. } else {
  498. $reimbursement["lastPayment"] = '--';
  499. $reimbursement["lastPaymentDate"] = '--';
  500. }
  501. }
  502. public function getAppointmentsPendingStatusChangeAck() {
  503. return Appointment::where('pro_id', $this->id)
  504. ->where('is_status_acknowledgement_from_appointment_pro_pending', true)
  505. //->where('raw_date', '>=', DB::raw('NOW()'))
  506. ->orderBy('raw_date', 'asc')
  507. ->get();
  508. }
  509. public function getAppointmentsPendingDecisionAck() {
  510. return Appointment::where('pro_id', $this->id)
  511. ->where('is_decision_acknowledgement_from_appointment_pro_pending', true)
  512. //->where('raw_date', '>=', DB::raw('NOW()'))
  513. ->orderBy('raw_date', 'asc')
  514. ->get();
  515. }
  516. public function getAppointmentsPendingTimeChangeAck() {
  517. return Appointment::where('pro_id', $this->id)
  518. ->where('is_time_change_acknowledgement_from_appointment_pro_pending', true)
  519. //->where('raw_date', '>=', DB::raw('NOW()'))
  520. ->orderBy('raw_date', 'asc')
  521. ->get();
  522. }
  523. public function getAccessibleClientsQuery($_search = false) {
  524. $proID = $this->id;
  525. $query = Client::whereNull('shadow_pro_id');
  526. if ($this->pro_type === 'ADMIN' && ($_search ? $this->can_see_any_client_via_search : $this->can_see_all_clients_in_list)) {
  527. $query = $query->where('id', '>', 0);
  528. } else {
  529. $query = $query->where(function ($q) use ($proID) {
  530. $q->where('mcp_pro_id', $proID)
  531. ->orWhere('cm_pro_id', $proID)
  532. ->orWhere('rmm_pro_id', $proID)
  533. ->orWhere('rme_pro_id', $proID)
  534. ->orWhere('physician_pro_id', $proID)
  535. ->orWhere('default_na_pro_id', $proID)
  536. ->orWhereRaw('id IN (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = ?)', [$proID])
  537. ->orWhereRaw('id IN (SELECT client_id FROM appointment WHERE status NOT IN (\'CANCELLED\') AND pro_id = ?)', [$proID])
  538. ->orWhereRaw('id IN (SELECT mcp_pro_id FROM client_program WHERE client_id = client.id AND is_active = TRUE)')
  539. ->orWhereRaw('id IN (SELECT manager_pro_id FROM client_program WHERE client_id = client.id AND is_active = TRUE)')
  540. ->orWhereRaw('id IN (SELECT client_id FROM note WHERE ally_pro_id = ? AND is_cancelled = FALSE)', [$proID]);;
  541. });
  542. }
  543. return $query;
  544. }
  545. public function canAccess($_patientUid) {
  546. $proID = $this->id;
  547. if ($this->pro_type === 'ADMIN') {
  548. return true;
  549. }
  550. $canAccess = Client::select('uid')
  551. ->where('uid', $_patientUid)
  552. ->where(function ($q) use ($proID) {
  553. $q->whereNull('mcp_pro_id')
  554. ->orWhere('mcp_pro_id', $proID)
  555. ->orWhere('cm_pro_id', $proID)
  556. ->orWhere('rmm_pro_id', $proID)
  557. ->orWhere('rme_pro_id', $proID)
  558. ->orWhere('physician_pro_id', $proID)
  559. ->orWhere('default_na_pro_id', $proID)
  560. ->orWhereRaw('id IN (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = ?)', [$proID])
  561. ->orWhereRaw('id IN (SELECT client_id FROM appointment WHERE status NOT IN (\'CANCELLED\') AND pro_id = ?)', [$proID])
  562. ->orWhereRaw('id IN (SELECT mcp_pro_id FROM client_program WHERE client_id = client.id AND is_active = TRUE)')
  563. ->orWhereRaw('id IN (SELECT manager_pro_id FROM client_program WHERE client_id = client.id AND is_active = TRUE)')
  564. ->orWhereRaw('id IN (SELECT client_id FROM note WHERE ally_pro_id = ? AND is_cancelled = FALSE)', [$proID]);
  565. })->count();
  566. return !!$canAccess;
  567. }
  568. public function canAddCPMEntryForMeasurement(Measurement $measurement, Pro $pro)
  569. {
  570. // check if client has any programs where this measurement type is allowed
  571. $allowed = false;
  572. $client = $measurement->client;
  573. $clientPrograms = $client->clientPrograms;
  574. if($pro->pro_type !== 'ADMIN') {
  575. $clientPrograms = $clientPrograms->filter(function($_clientProgram) use ($pro) {
  576. return $_clientProgram->manager_pro_id === $pro->id;
  577. });
  578. }
  579. if(count($clientPrograms)) {
  580. foreach ($clientPrograms as $clientProgram) {
  581. if(strpos(strtolower($clientProgram->measurement_labels), '|' . strtolower($measurement->label) . '|') !== FALSE) {
  582. $allowed = true;
  583. break;
  584. }
  585. }
  586. }
  587. return $allowed ? $clientPrograms : FALSE;
  588. }
  589. public function getUnstampedMeasurementsFromCurrentMonth($_countOnly, $skip, $limit)
  590. {
  591. date_default_timezone_set('US/Eastern');
  592. $start = strtotime(date('Y-m-01'));
  593. $end = date_add(date_create(date('Y-m-01')), date_interval_create_from_date_string("1 month"))->getTimestamp();
  594. $start *= 1000;
  595. $end *= 1000;
  596. $measurementsQuery = Measurement::where('measurement.is_active', true)
  597. ->join('client', 'client.id', '=', 'measurement.client_id')
  598. ->whereNotNull('measurement.client_bdt_measurement_id')
  599. ->whereNotNull('measurement.ts')
  600. ->where('measurement.is_cellular_zero', false)
  601. ->where('measurement.ts', '>=', $start)
  602. ->where('measurement.ts', '<', $end)
  603. ->whereIn('measurement.client_id', $this->getMyClientIds())
  604. ->where(function ($q) {
  605. $q
  606. ->where(function ($q2) {
  607. $q2
  608. ->where('client.mcp_pro_id', $this->id)
  609. ->where('measurement.has_been_stamped_by_mcp', false);
  610. })
  611. ->orWhere(function ($q2) {
  612. $q2
  613. ->where('client.default_na_pro_id', $this->id)
  614. ->where('measurement.has_been_stamped_by_non_hcp', false);
  615. })
  616. ->orWhere(function ($q2) {
  617. $q2
  618. ->where('client.rmm_pro_id', $this->id)
  619. ->where('measurement.has_been_stamped_by_rmm', false);
  620. })
  621. ->orWhere(function ($q2) {
  622. $q2
  623. ->where('client.rme_pro_id', $this->id)
  624. ->where('measurement.has_been_stamped_by_rme', false);
  625. });
  626. });
  627. if($_countOnly) {
  628. return $measurementsQuery->count();
  629. }
  630. $x = [];
  631. $measurements = $measurementsQuery
  632. ->orderBy('ts', 'desc')
  633. ->skip($skip)
  634. ->take($limit)
  635. ->get();
  636. // eager load stuff needed in JS
  637. foreach ($measurements as $measurement) {
  638. // if ($measurement->client_bdt_measurement_id) {
  639. // $measurement->bdtMeasurement = $measurement->clientBDTMeasurement->measurement;
  640. // }
  641. unset($measurement->clientBDTMeasurement); // we do not need this travelling to the frontend
  642. $client = [
  643. "uid" => $measurement->client->uid,
  644. "name" => $measurement->client->displayName(),
  645. ];
  646. $measurement->patient = $client;
  647. $measurement->careMonth = $measurement->client->currentCareMonth();
  648. $measurement->timestamp = friendlier_date_time($measurement->created_at);
  649. unset($measurement->client); // we do not need this travelling to the frontend
  650. if(@$measurement->detail_json) unset($measurement->detail_json);
  651. if(@$measurement->canvas_data) unset($measurement->canvas_data);
  652. if(@$measurement->latest_measurements) unset($measurement->latest_measurements);
  653. if(@$measurement->info_lines) unset($measurement->info_lines);
  654. if(@$measurement->canvas_data_backup) unset($measurement->canvas_data_backup);
  655. if(@$measurement->migrated_canvas_data_backup) unset($measurement->migrated_canvas_data_backup);
  656. // if($measurement->label == 'SBP' || $measurement->label = 'DBP'){
  657. // continue;
  658. // }
  659. $x[] = $measurement;
  660. }
  661. // dd($measurements);
  662. return $measurements;
  663. }
  664. public function getMeasurements($_onlyUnstamped = true)
  665. {
  666. $measurementsQuery = Measurement::where('is_removed', false);
  667. if ($this->pro_type != 'ADMIN') {
  668. $measurementsQuery
  669. ->whereIn('client_id', $this->getMyClientIds());
  670. }
  671. if ($_onlyUnstamped) {
  672. $measurementsQuery
  673. ->whereNotNull('client_bdt_measurement_id')
  674. ->whereNotNull('ts')
  675. ->where('is_cellular_zero', false)
  676. ->where(function ($q) {
  677. $q->whereNull('status')
  678. ->orWhere(function ($q2) {
  679. $q2->where('status', '<>', 'ACK')
  680. ->where('status', '<>', 'INVALID_ACK');
  681. });
  682. });
  683. }
  684. $x = [];
  685. $measurements = $measurementsQuery->orderBy('ts', 'desc')->paginate(50);
  686. // eager load stuff needed in JS
  687. foreach ($measurements as $measurement) {
  688. // if ($measurement->client_bdt_measurement_id) {
  689. // $measurement->bdtMeasurement = $measurement->clientBDTMeasurement->measurement;
  690. // }
  691. unset($measurement->clientBDTMeasurement); // we do not need this travelling to the frontend
  692. $client = [
  693. "uid" => $measurement->client->uid,
  694. "name" => $measurement->client->displayName(),
  695. ];
  696. $measurement->patient = $client;
  697. $measurement->careMonth = $measurement->client->currentCareMonth();
  698. $measurement->timestamp = friendly_date_time($measurement->created_at);
  699. unset($measurement->client); // we do not need this travelling to the frontend
  700. // if($measurement->label == 'SBP' || $measurement->label = 'DBP'){
  701. // continue;
  702. // }
  703. $x[] = $measurement;
  704. }
  705. return $measurements;
  706. }
  707. public function companyPros()
  708. {
  709. return $this->hasMany(CompanyPro::class, 'pro_id', 'id')
  710. ->where('is_active', true);
  711. }
  712. public function companyProPayers()
  713. {
  714. return $this->hasMany(CompanyProPayer::class, 'pro_id', 'id');
  715. }
  716. public function isAssociatedWithMCPayer() {
  717. $companyProPayers = $this->companyProPayers;
  718. $foundMC = false;
  719. if($companyProPayers) {
  720. foreach ($companyProPayers as $companyProPayer) {
  721. if($companyProPayer->payer && $companyProPayer->payer->is_medicare) {
  722. $foundMC = true;
  723. break;
  724. }
  725. }
  726. }
  727. return $foundMC;
  728. }
  729. public function isAssociatedWithNonMCPayer($_payerID) {
  730. $companyProPayers = $this->companyProPayers;
  731. $foundNonMC = false;
  732. if($companyProPayers) {
  733. foreach ($companyProPayers as $companyProPayer) {
  734. if($companyProPayer->payer && !$companyProPayer->payer->is_medicare && $companyProPayer->payer->id === $_payerID) {
  735. $foundNonMC = true;
  736. break;
  737. }
  738. }
  739. }
  740. return $foundNonMC;
  741. }
  742. public function companyLocations() {
  743. $companyProPayers = $this->companyProPayers;
  744. $companyIDs = [];
  745. foreach ($companyProPayers as $companyProPayer) {
  746. $companyIDs[] = $companyProPayer->company_id;
  747. }
  748. $locations = [];
  749. if(count($companyIDs)) {
  750. $locations = CompanyLocation::whereIn('id', $companyIDs)->get();
  751. }
  752. return $locations;
  753. }
  754. public function shadowClient() {
  755. return $this->hasOne(Client::class, 'id', 'shadow_client_id');
  756. }
  757. public function defaultCompanyPro() {
  758. return $this->hasOne(CompanyPro::class, 'id', 'default_company_pro_id');
  759. }
  760. public function currentNotePickupForProcessing() {
  761. return $this->hasOne(NotePickupForProcessing::class, 'id', 'current_note_pickup_for_processing_id');
  762. }
  763. public function get_patients_not_seen_in_45_days_count_as_mcp(){
  764. return 0;
  765. }
  766. //DNA_DASHBOARD
  767. //queries
  768. private function patientsQueryAsDna(){
  769. // WHERE na_pro_id = :me.id
  770. return Client::where('default_na_pro_id', $this->id);
  771. }
  772. private function patientsAwaitingMcpVisitQueryAsDna(){
  773. // WHERE has_mcp_done_onboarding_visit <> 'YES'
  774. return Client::where('default_na_pro_id', $this->id)->where('has_mcp_done_onboarding_visit', '<>', 'YES');
  775. }
  776. private function patientsWithoutAppointmentQueryAsDna(){
  777. // WHERE today_mcp_appointment_date IS NULL AND next_mcp_appointment_date IS NULL
  778. return Client::where('default_na_pro_id', $this->id)
  779. ->whereNull('today_mcp_appointment_date')
  780. ->whereNull('next_mcp_appointment_date');
  781. }
  782. private function encountersPendingMyReviewQueryAsDna(){
  783. // 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;
  784. return Note::where('ally_pro_id', $this->id)
  785. ->where('is_cancelled', '<>', true)
  786. ->where('is_signed_by_hcp', true)
  787. ->where('is_signed_by_ally','<>', true);
  788. }
  789. private function encountersInProgressQueryAsDna(){
  790. // 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;
  791. return Note::where('ally_pro_id', $this->id)
  792. ->where('is_cancelled', '<>', true)
  793. ->where('is_signed_by_hcp', '<>', true);
  794. }
  795. private function appointmentsPendingConfirmationQueryAsDna(){
  796. // WHERE client_id IN (SELECT id FROM client WHERE default_na_pro_id = :me.id) AND status = 'PENDING'
  797. $myId = $this->id;
  798. return Appointment::whereHas('client', function($clientQuery) use ($myId) {
  799. return $clientQuery->where('default_na_pro_id', $myId);
  800. })->where('status', 'PENDING');
  801. }
  802. private function cancelledAppointmentsPendingAckQueryAsDna(){
  803. // 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;
  804. $myId = $this->id;
  805. return Appointment::whereHas('client', function($clientQuery) use ($myId) {
  806. return $clientQuery->where('default_na_pro_id', $myId);
  807. })->where('status', 'CANCELLED')
  808. ->where('is_status_acknowledgement_from_default_na_pending', true);
  809. }
  810. private function reportsPendingAckQueryAsDna(){
  811. // 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
  812. $myId = $this->id;
  813. return IncomingReport::whereHas('client',function($clientQuery) use ($myId) {
  814. return $clientQuery->where('default_na_pro_id', $myId);
  815. })->where('has_na_pro_signed', '<>', true)
  816. ->where('is_entry_error','<>', true);
  817. }
  818. private function supplyOrdersPendingMyAckQueryAsDna(){
  819. // 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;
  820. $myId = $this->id;
  821. return SupplyOrder::whereHas('client',function($clientQuery) use ($myId) {
  822. return $clientQuery->where('default_na_pro_id', $myId);
  823. })->where('has_na_pro_signed', '<>', true)
  824. ->where('is_signed_by_pro', true)
  825. ->where('is_cancelled', '<>', true);
  826. }
  827. private function supplyOrdersPendingHcpApprovalQueryAsDna(){
  828. // 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;
  829. $myId = $this->id;
  830. return SupplyOrder::whereHas('client',function($clientQuery) use ($myId) {
  831. return $clientQuery->where('default_na_pro_id', $myId);
  832. })->where('has_na_pro_signed', true)
  833. ->where('is_signed_by_pro','<>', true)
  834. ->where('is_cancelled', '<>', true);
  835. }
  836. //counts
  837. public function patientsCountAsDna(){
  838. return $this->patientsQueryAsDna()->count();
  839. }
  840. public function patientsAwaitingMcpVisitCountAsDna(){
  841. return $this->patientsAwaitingMcpVisitQueryAsDna()->count();
  842. }
  843. public function patientsWithoutAppointmentCountAsDna(){
  844. return $this->patientsWithoutAppointmentQueryAsDna()->count();
  845. }
  846. public function encountersPendingMyReviewCountAsDna(){
  847. return $this->encountersPendingMyReviewQueryAsDna()->count();
  848. }
  849. public function encountersInProgressCountAsDna(){
  850. return $this->encountersInProgressQueryAsDna()->count();
  851. }
  852. public function appointmentsPendingConfirmationCountAsDna(){
  853. return $this->appointmentsPendingConfirmationQueryAsDna()->count();
  854. }
  855. public function cancelledAppointmentsPendingAckCountAsDna(){
  856. return $this->cancelledAppointmentsPendingAckQueryAsDna()->count();
  857. }
  858. public function reportsPendingAckCountAsDna(){
  859. return $this->reportsPendingAckQueryAsDna()->count();
  860. }
  861. public function supplyOrdersPendingMyAckCountAsDna(){
  862. return $this->supplyOrdersPendingMyAckQueryAsDna()->count();
  863. }
  864. public function supplyOrdersPendingHcpApprovalCountAsDna(){
  865. return $this->supplyOrdersPendingHcpApprovalQueryAsDna()->count();
  866. }
  867. //records
  868. private $DNA_RESULTS_PAGE_SIZE = 50;
  869. public function patientsRecordsAsDna(){
  870. return $this->patientsQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  871. }
  872. public function patientsAwaitingMcpVisitRecordsAsDna(){
  873. return $this->patientsAwaitingMcpVisitQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  874. }
  875. public function patientsWithoutAppointmentRecordsAsDna(){
  876. return $this->patientsWithoutAppointmentQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  877. }
  878. public function encountersPendingMyReviewRecordsAsDna(){
  879. return $this->encountersPendingMyReviewQueryAsDna()
  880. ->orderBy('effective_dateest', 'desc')
  881. ->orderBy('created_at', 'desc')
  882. ->paginate($this->DNA_RESULTS_PAGE_SIZE);
  883. }
  884. public function encountersInProgressRecordsAsDna(){
  885. return $this->encountersInProgressQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  886. }
  887. public function appointmentsPendingConfirmationRecordsAsDna(){
  888. return $this->appointmentsPendingConfirmationQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  889. }
  890. public function cancelledAppointmentsPendingAckRecordsAsDna(){
  891. return $this->cancelledAppointmentsPendingAckQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  892. }
  893. public function reportsPendingAckRecordsAsDna(){
  894. return $this->reportsPendingAckQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  895. }
  896. public function supplyOrdersPendingMyAckRecordsAsDna(){
  897. return $this->supplyOrdersPendingMyAckQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  898. }
  899. public function supplyOrdersPendingHcpApprovalRecordsAsDna(){
  900. return $this->supplyOrdersPendingHcpApprovalQueryAsDna()->paginate($this->DNA_RESULTS_PAGE_SIZE);
  901. }
  902. public function measurementsPendingReviewAsDna(){
  903. //Measurements Pending Review
  904. // SELECT * FROM measurement WHERE client_id IN (SELECT id FROM client WHERE rmm_pro_id = :me.id)
  905. // 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;
  906. $myId = $this->id;
  907. return Measurement::whereHas('client',function($clientQuery) use ($myId) {
  908. return $clientQuery->where('rmm_pro_id', $myId);
  909. })
  910. ->where('has_been_stamped_by_rmm', '<>', true)
  911. ->where('is_cellular', true)
  912. ->where('is_cellular_zero', '<>', true)
  913. ->where('is_active', true)
  914. ->orderBy('ts', 'DESC')
  915. ->paginate(15);
  916. }
  917. public function getProcessingAmountAsDna(){
  918. $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;
  919. $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;
  920. $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;
  921. $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;
  922. $totalExpectedAmount = $expectedForCm + $expectedForRme + $expectedForRmm + $expectedForNa;
  923. return $totalExpectedAmount;
  924. }
  925. public function getNextPaymentDateAsDna(){
  926. $nextPaymentDate = '--';
  927. //if today is < 15th, next payment is 15th, else nextPayment is
  928. $today = strtotime(date('Y-m-d'));
  929. $todayDate = date('j', $today);
  930. $todayMonth = date('m', $today);
  931. $todayYear = date('Y', $today);
  932. if ($todayDate < 15) {
  933. $nextPaymentDate = new DateTime();
  934. $nextPaymentDate->setDate($todayYear, $todayMonth, 15);
  935. $nextPaymentDate = $nextPaymentDate->format('m/d/Y');
  936. } else {
  937. $nextPaymentDate = new \DateTime();
  938. $lastDayOfMonth = date('t', $today);
  939. $nextPaymentDate->setDate($todayYear, $todayMonth, $lastDayOfMonth);
  940. $nextPaymentDate = $nextPaymentDate->format('m/d/Y');
  941. }
  942. return $nextPaymentDate;
  943. }
  944. public function clientSmsesAsDna(){
  945. $myId = $this->id;
  946. return ClientSMS::whereHas('client', function($clientQuery) use ($myId){
  947. return $clientQuery->where('default_na_pro_id', $myId);
  948. })
  949. ->orderBy('created_at', 'DESC')
  950. ->paginate(15);
  951. }
  952. public function clientMemosAsDna(){
  953. $naClientMemos = DB::select(
  954. DB::raw("
  955. SELECT c.uid as client_uid, c.name_first, c.name_last,
  956. cm.uid, cm.content, cm.created_at
  957. FROM client c join client_memo cm on c.id = cm.client_id
  958. WHERE
  959. c.default_na_pro_id = {$this->id}
  960. ORDER BY cm.created_at DESC
  961. ")
  962. );
  963. return $naClientMemos;
  964. }
  965. public function getAppointmentsPendingStatusChangeAckAsDna() {
  966. $myId = $this->id;
  967. return Appointment::whereHas('client', function($clientQuery) use ($myId){
  968. return $clientQuery->where('default_na_pro_id', $myId);
  969. })
  970. ->where('is_status_acknowledgement_from_appointment_pro_pending', true)
  971. ->where('raw_date', '>=', DB::raw('NOW()'))
  972. ->orderBy('raw_date', 'asc')
  973. ->get();
  974. }
  975. public function getAppointmentsPendingDecisionAckAsDna() {
  976. $myId = $this->id;
  977. return Appointment::whereHas('client', function($clientQuery) use ($myId){
  978. return $clientQuery->where('default_na_pro_id', $myId);
  979. })
  980. ->where('is_decision_acknowledgement_from_appointment_pro_pending', true)
  981. ->where('raw_date', '>=', DB::raw('NOW()'))
  982. ->orderBy('raw_date', 'asc')
  983. ->get();
  984. }
  985. public function getAppointmentsPendingTimeChangeAckAsDna() {
  986. $myId = $this->id;
  987. return Appointment::whereHas('client', function($clientQuery) use ($myId){
  988. return $clientQuery->where('default_na_pro_id', $myId);
  989. })
  990. ->where('is_time_change_acknowledgement_from_appointment_pro_pending', true)
  991. ->where('raw_date', '>=', DB::raw('NOW()'))
  992. ->orderBy('raw_date', 'asc')
  993. ->get();
  994. }
  995. function myGenericBills() {
  996. return Bill::where('bill_service_type', 'GENERIC')
  997. ->where('generic_pro_id', $this->id)
  998. ->orderBy('created_at', 'DESC')->get();
  999. }
  1000. }