Bladeren bron

Merge branch 'dev' of https://rav.triplestart.com/jmudaka/stagfe2 into dev

Samson Mutunga 3 jaren geleden
bovenliggende
commit
53c7f478cd
100 gewijzigde bestanden met toevoegingen van 12882 en 1328 verwijderingen
  1. 0 2
      .env-example
  2. 0 57
      .env.example
  3. 1 0
      .gitignore
  4. 561 0
      app/Helpers/fdb.php
  5. 40 0
      app/Helpers/helpers.php
  6. 16 0
      app/Http/Controllers/AppointmentController.php
  7. 0 1
      app/Http/Controllers/Controller.php
  8. 726 0
      app/Http/Controllers/FDBPGController.php
  9. 161 28
      app/Http/Controllers/HomeController.php
  10. 76 0
      app/Http/Controllers/NoteController.php
  11. 103 1
      app/Http/Controllers/PatientController.php
  12. 238 10
      app/Http/Controllers/PracticeManagementController.php
  13. 17 0
      app/Http/Middleware/ProAuthenticated.php
  14. 4 0
      app/Models/AppointmentConfirmationDecision.php
  15. 6 0
      app/Models/CareMonth.php
  16. 149 3
      app/Models/Client.php
  17. 58 0
      app/Models/ClientPrimaryCoverage.php
  18. 31 0
      app/Models/Erx.php
  19. 29 0
      app/Models/Note.php
  20. 5 0
      app/Models/NotePickupForProcessing.php
  21. 11 0
      app/Models/NotePoint.php
  22. 169 0
      app/Models/Point.php
  23. 29 0
      app/Models/Pro.php
  24. 25 0
      app/Models/ProTeam.php
  25. 22 0
      app/Models/Segment.php
  26. 11 0
      app/Models/SegmentTemplate.php
  27. 10 0
      app/Models/VisitTemplate.php
  28. 2 1
      composer.json
  29. 5 1
      config/app.php
  30. 15 0
      config/database.php
  31. 347 0
      fdb_notes.txt
  32. 231 16
      public/css/style.css
  33. 8 3
      public/js/mc.js
  34. 6 4
      public/js/pro-suggest.js
  35. 22 0
      public/js/show-on-click.js
  36. 4 4
      public/js/stag-popup.js
  37. 191 0
      public/js/stag-suggest.js
  38. 0 0
      public/js/yemi.js
  39. 213 13
      resources/views/app/dashboard.blade.php
  40. 8 33
      resources/views/app/dashboard/incoming_reports.blade.php
  41. 63 61
      resources/views/app/dashboard/measurements.blade.php
  42. 12 0
      resources/views/app/fdb-pg/fdb-allergy-suggest.blade.php
  43. 16 0
      resources/views/app/fdb-pg/fdb-coadministration.blade.php
  44. 25 0
      resources/views/app/fdb-pg/fdb-contraindications.blade.php
  45. 12 0
      resources/views/app/fdb-pg/fdb-dx-suggest.blade.php
  46. 27 0
      resources/views/app/fdb-pg/fdb-geriatric-precautions.blade.php
  47. 25 0
      resources/views/app/fdb-pg/fdb-indications.blade.php
  48. 12 0
      resources/views/app/fdb-pg/fdb-med-suggest.blade.php
  49. 667 0
      resources/views/app/fdb-pg/fdb-rx.blade.php
  50. 27 0
      resources/views/app/fdb-pg/fdb-side-effects.blade.php
  51. 17 6
      resources/views/app/generic-bills/add-bill-form/Note.blade.php
  52. 11 5
      resources/views/app/generic-bills/add-bill-form/_default-fields.blade.php
  53. 14 0
      resources/views/app/generic-bills/add-bill-form/_default-script.blade.php
  54. 10 1
      resources/views/app/generic-bills/inline.blade.php
  55. 33 17
      resources/views/app/guest/appointment-confirmation.blade.php
  56. 2 2
      resources/views/app/new-non-mcn-patient.blade.php
  57. 752 5
      resources/views/app/new-patient.blade.php
  58. 48 9
      resources/views/app/patient/appointment-calendar.blade.php
  59. 1 1
      resources/views/app/patient/canvas-sections/fhx/summary.php
  60. 0 1
      resources/views/app/patient/canvas-sections/rx/form.blade.php
  61. 286 0
      resources/views/app/patient/care-month/_matrix.blade.php
  62. 218 12
      resources/views/app/patient/care-month/dashboard.blade.php
  63. 5 0
      resources/views/app/patient/care-month/matrix.blade.php
  64. 10 0
      resources/views/app/patient/care-months.blade.php
  65. 3 2
      resources/views/app/patient/claims-resolver.blade.php
  66. 875 0
      resources/views/app/patient/client-primary-coverages.blade.php
  67. 168 42
      resources/views/app/patient/dashboard.blade.php
  68. 19 15
      resources/views/app/patient/incoming-reports.blade.php
  69. 435 0
      resources/views/app/patient/medications-center.blade.php
  70. 67 59
      resources/views/app/patient/note/_create-bill.blade.php
  71. 42 0
      resources/views/app/patient/note/_templates-v2-index.blade.php
  72. 2131 0
      resources/views/app/patient/note/dashboard-univ.blade.php
  73. 857 805
      resources/views/app/patient/note/dashboard.blade.php
  74. 50 6
      resources/views/app/patient/note/dashboard_script.blade.php
  75. 2 0
      resources/views/app/patient/note/note-section-list.blade.php
  76. 8 0
      resources/views/app/patient/note/note-segment-list.blade.php
  77. 433 0
      resources/views/app/patient/note/pdf.blade.php
  78. 35 0
      resources/views/app/patient/note/plan-log.blade.php
  79. 35 0
      resources/views/app/patient/note/review-log.blade.php
  80. 34 24
      resources/views/app/patient/note/section.blade.php
  81. 1 2
      resources/views/app/patient/note/section_script.blade.php
  82. 147 0
      resources/views/app/patient/note/segment.blade.php
  83. 369 0
      resources/views/app/patient/note/segment_script.blade.php
  84. 199 0
      resources/views/app/patient/note/sign-confirmation.blade.php
  85. 110 70
      resources/views/app/patient/notes.blade.php
  86. 78 0
      resources/views/app/patient/page-sections/cc/form.blade.php
  87. 23 0
      resources/views/app/patient/page-sections/cc/summary.php
  88. 121 0
      resources/views/app/patient/page-sections/rx/form.blade.php
  89. 45 0
      resources/views/app/patient/page-sections/rx/summary.php
  90. 78 0
      resources/views/app/patient/page-sections/subjective/form.blade.php
  91. 23 0
      resources/views/app/patient/page-sections/subjective/summary.php
  92. 20 0
      resources/views/app/patient/page-sections/vitals/default.php
  93. 264 0
      resources/views/app/patient/page-sections/vitals/form.blade.php
  94. 131 0
      resources/views/app/patient/page-sections/vitals/summary.php
  95. 9 2
      resources/views/app/patient/partials/appointment-confirmation-history.blade.php
  96. 2 2
      resources/views/app/patient/partials/appointment-confirmation.blade.php
  97. 6 2
      resources/views/app/patient/partials/appointment-request-confirmation.blade.php
  98. 126 0
      resources/views/app/patient/partials/latest-vitals.blade.php
  99. 32 0
      resources/views/app/patient/prescriptions/client-status-form.blade.php
  100. 61 0
      resources/views/app/patient/prescriptions/drug-form.blade.php

+ 0 - 2
.env-example

@@ -53,5 +53,3 @@ AUTH_URL="http://localhost:3002"
 BACKEND_WS_URL=http://localhost:8080/ws
 AGORA_APPID=9d04292b03524927a8fe9d937a448d85
 AGORA_MODE=screen
-
-ENABLE_SOCKETS=false

+ 0 - 57
.env.example

@@ -1,57 +0,0 @@
-APP_NAME=Stag
-APP_ENV=local
-APP_KEY=base64:1yKRgeLWTeEXTfh51vXtJaf6GJaRUn4NHzdlOdyDpRY=
-APP_DEBUG=true
-APP_URL=http://localhost
-
-LOG_CHANNEL=stack
-
-DB_CONNECTION=pgsql
-DB_HOST=127.0.0.1
-DB_PORT=5432
-DB_DATABASE=stag2
-DB_USERNAME=postgres
-DB_PASSWORD=pass
-
-BROADCAST_DRIVER=log
-CACHE_DRIVER=file
-QUEUE_CONNECTION=sync
-SESSION_DRIVER=file
-SESSION_LIFETIME=120
-
-REDIS_HOST=127.0.0.1
-REDIS_PASSWORD=null
-REDIS_PORT=6379
-
-MAIL_MAILER=smtp
-MAIL_HOST=smtp.mailtrap.io
-MAIL_PORT=2525
-MAIL_USERNAME=null
-MAIL_PASSWORD=null
-MAIL_ENCRYPTION=null
-MAIL_FROM_ADDRESS=null
-MAIL_FROM_NAME="${APP_NAME}"
-
-AWS_ACCESS_KEY_ID=
-AWS_SECRET_ACCESS_KEY=
-AWS_DEFAULT_REGION=us-east-1
-AWS_BUCKET=
-
-PUSHER_APP_ID=
-PUSHER_APP_KEY=
-PUSHER_APP_SECRET=
-PUSHER_APP_CLUSTER=mt1
-
-MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
-MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
-
-BACKEND_URL="http://localhost:8080/api"
-ADMIN_PORTAL_URL="http://localhost:3000"
-
-AUTH_URL="http://localhost:3002"
-
-BACKEND_WS_URL=http://localhost:8080/ws
-AGORA_APPID=9d04292b03524927a8fe9d937a448d85
-AGORA_MODE=screen
-
-ENABLE_SOCKETS=false

+ 1 - 0
.gitignore

@@ -15,3 +15,4 @@ yarn-error.log
 /public/fullcalendar-5.3.2/examples/
 /public/fullcalendar-5.3.2/LICENSE.txt
 /public/fullcalendar-5.3.2/README.md
+/page-sections

+ 561 - 0
app/Helpers/fdb.php

@@ -0,0 +1,561 @@
+<?php
+
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\DB;
+
+if(!function_exists('side_effects_info')) {
+    function side_effects_info($_drugs) {
+
+        $result = [];
+
+        // collect gcn-seq-nos
+        $gcnSeqNos = [];
+        $rxMap = [];
+        foreach ($_drugs as $drug) {
+            if(@$drug->data && $drug->data->gcnSeqno) {
+                $gcnSeqNos[] = $drug->data->gcnSeqno;
+                $rxMap[$drug->data->gcnSeqno] = $drug->data->name;
+            }
+        }
+        if(!count($gcnSeqNos)) return $result;
+
+        $gcnSeqNos = implode(',', array_map(function($_x) {
+            return "'" . $_x . "'";
+        }, $gcnSeqNos));
+
+        $sides = DB::connection('pgsql_fdb')->select("
+SELECT r1.gcn_seqno, r1.side, sm.side_freq, sm.side_sev, sm.dxid, dx.dxid_desc56
+FROM rsidegc0_gcnseqno_link r1
+    JOIN rsidema3_mstr sm ON r1.side = sm.side
+    JOIN rfmldx0_dxid dx ON sm.dxid = dx.dxid
+WHERE r1.gcn_seqno IN (" . $gcnSeqNos . ")
+ORDER BY r1.gcn_seqno, sm.side_sev DESC, sm.side_freq ASC
+            "
+        );
+
+        $seMap = [];
+
+        foreach ($sides as $se) {
+
+            if(!isset($seMap[$rxMap[$se->gcn_seqno]])) {
+                $seMap[$rxMap[$se->gcn_seqno]] = [];
+            }
+
+            $seMap[$rxMap[$se->gcn_seqno]][] = [
+                "gcn_seqno" => $se->gcn_seqno,
+                "side_freq" => $se->side_freq,
+                "side_sev" => $se->side_sev,
+                "dxid_desc56" => $se->dxid_desc56,
+            ];
+        }
+
+        $result = $seMap;
+
+        return $result;
+    }
+}
+
+if(!function_exists('precautions_info')) {
+    function precautions_info($_drugs) {
+
+    }
+}
+
+if(!function_exists('contraindications_info')) {
+    function contraindications_info($_drugs) {
+
+        $result = [];
+
+        // collect routed med ids
+        $routedMedIds = [];
+        $rxMap = [];
+        foreach ($_drugs as $drug) {
+            if(@$drug->data && $drug->data->routedMedId) {
+                $routedMedIds[] = $drug->data->routedMedId;
+                $rxMap[$drug->data->routedMedId] = $drug->data->name;
+            }
+        }
+        if(!count($routedMedIds)) return $result;
+
+        $routedMedIds = implode(',', array_map(function($_x) {
+            return "'" . $_x . "'";
+        }, $routedMedIds));
+
+        $contraindications = DB::connection('pgsql_fdb')->select("
+SELECT r1.routed_med_id, r1.ddxcn, r2.dxid, r2.ddxcn_sl, r3.dxid_desc56
+FROM rddcmrm0_routed_med_link r1
+    JOIN rddcmma1_contra_mstr r2 ON r1.ddxcn = r2.ddxcn
+    JOIN rfmldx0_dxid r3 ON r2.dxid = r3.dxid
+WHERE r1.routed_med_id IN (" . $routedMedIds . ")
+ORDER BY r1.routed_med_id, r3.dxid_desc56, r2.ddxcn_sl
+            "
+        );
+
+        $ciMap = [];
+
+        foreach ($contraindications as $ci) {
+
+            if(!isset($ciMap[$rxMap[$ci->routed_med_id]])) {
+                $ciMap[$rxMap[$ci->routed_med_id]] = [];
+            }
+
+            $ciMap[$rxMap[$ci->routed_med_id]][] = [
+                "dxid_desc56" => $ci->dxid_desc56,
+            ];
+        }
+
+        $result = $ciMap;
+
+        return $result;
+
+    }
+}
+
+if(!function_exists('drug_allergy_info')) {
+    function drug_allergy_info($_drugs, $_allergies) {
+        $output = [];
+
+        /*
+        for each allergy
+            if damConceptIdType = 1 // allergen-group-id
+                // https://docs.fdbhealth.com/display/MKDOCUS/Screening+an+NDC+for+a+DAM_ALRGN_GRP+Allergen+-+Illustration+of+Scenario+C
+                ...
+            elseif damConceptIdType = 2 // medication-name-id
+                // https://docs.fdbhealth.com/display/MKDOCUS/Screening+an+NDC+for+a+MED_NAME_ID+Allergen+-+Illustration+of+Scenario+B
+                ...
+            elseif damConceptIdType = 6 // base-ingredient-id
+                // https://docs.fdbhealth.com/display/MKDOCUS/Screening+an+NDC+for+an+Ingredient+Allergen+-+Illustration+of+Scenario+A
+                ...
+            endif
+        endfor
+        */
+
+        foreach ($_allergies as $allergy) {
+            foreach ($_drugs as $rxItem) {
+                if($allergy->data->damConceptIdType == 6) { // ingredient
+                    if (drugAllergyIngredientAllergenVsSingleRx($allergy, $rxItem)) {
+                        $output[] = "<b>{$rxItem->data->name}</b> can cause allergic reactions since the patient is allergic to <b>{$allergy->data->name}</b>.";
+                    }
+                }
+                else if($allergy->data->damConceptIdType == 2) { // medication
+                    if (drugAllergyMedicationAllergenVsSingleRx($allergy, $rxItem)) {
+                        $output[] = "<b>{$rxItem->data->name}</b> can cause allergic reactions since the patient is allergic to <b>{$allergy->data->name}</b>.";
+                    }
+                }
+                else if($allergy->data->damConceptIdType == 1) { // allergen group
+                    if (drugAllergyGroupAllergenVsSingleRx($allergy, $rxItem)) {
+                        $output[] = "<b>{$rxItem->data->name}</b> can cause allergic reactions since the patient is allergic to <b>{$allergy->data->name}</b>.";
+                    }
+                }
+            }
+        }
+
+        return implode("<br>", $output);
+    }
+}
+if(!function_exists('drugAllergyIngredientAllergenVsSingleRx')) {
+    function drugAllergyIngredientAllergenVsSingleRx($_allergen, $_rx)
+    {
+
+        $matches = DB::connection('pgsql_fdb')->select("
+    (
+        -- ingredients from medication
+        SELECT R1.related_hic_seqn as hic_seqn, R2.hic_desc
+        FROM RHICHCR0_HIC_HIC_LINK R1
+                 JOIN RHICD5_HIC_DESC R2 ON R1.related_hic_seqn = R2.hic_seqn
+        WHERE R1.hic_seqn IN (
+            SELECT S2.dam_alrgn_hic_seqn
+            FROM RMEDMHL0_MED_HICLSEQNO_LINK S1
+                     JOIN RDAMHHA0_HIC_HICL_ALG_LINK S2 ON S1.hicl_seqno = S2.hicl_seqno
+            WHERE S1.med_concept_id = :medid
+              AND S1.med_concept_id_typ = 3
+        )
+    )
+    INTERSECT
+    (
+        -- all ingredients directly and related from allergens
+        (
+            SELECT R1.related_hic_seqn as hic_seqn, R2.hic_desc
+            FROM RHICHCR0_HIC_HIC_LINK R1
+                     JOIN RHICD5_HIC_DESC R2 ON R1.related_hic_seqn = R2.hic_seqn
+            WHERE R1.hic_seqn = :allergenConceptID
+        )
+        UNION
+        -- all ingredients via related dam allergen groups
+        (
+            SELECT r3.hic_seqn, r4.hic_desc
+            FROM RDAMGHC0_HIC_ALRGN_GRP_LINK R1
+                     JOIN rdamagd1_alrgn_grp_desc R2 on R1.dam_alrgn_grp = R2.dam_alrgn_grp
+                     JOIN RDAMGHC0_HIC_ALRGN_GRP_LINK R3 on R1.dam_alrgn_grp = R3.dam_alrgn_grp
+                     JOIN RHICD5_HIC_DESC R4 on r3.hic_seqn = r4.hic_seqn
+            WHERE R1.hic_seqn = :allergenConceptID
+              AND R2.dam_alrgn_grp_status_cd = 0
+            ORDER BY r3.hic_seqn
+        )
+    )
+    ",
+            ['medid' => $_rx->data->medId, 'allergenConceptID' => $_allergen->data->damConceptId]
+        );
+
+        return !!count($matches);
+    }
+}
+if(!function_exists('drugAllergyMedicationAllergenVsSingleRx')) {
+    function drugAllergyMedicationAllergenVsSingleRx($_allergen, $_rx)
+    {
+
+        $matches = DB::connection('pgsql_fdb')->select("
+    (
+        -- ingredients from medication
+        SELECT R1.related_hic_seqn as hic_seqn
+        FROM RHICHCR0_HIC_HIC_LINK R1
+                 JOIN RHICD5_HIC_DESC R2 ON R1.related_hic_seqn = R2.hic_seqn
+        WHERE R1.hic_seqn IN (
+            SELECT S2.dam_alrgn_hic_seqn
+            FROM RMEDMHL0_MED_HICLSEQNO_LINK S1
+                     JOIN RDAMHHA0_HIC_HICL_ALG_LINK S2 ON S1.hicl_seqno = S2.hicl_seqno
+            WHERE S1.med_concept_id = :medid
+              AND S1.med_concept_id_typ = 3
+        )
+    )
+    INTERSECT
+    (
+        -- all ingredients directly and related from allergens
+        SELECT R1.dam_alrgn_hic_seqn as hic_seqn
+        FROM RDAMHHA0_HIC_HICL_ALG_LINK R1
+        WHERE R1.hicl_seqno IN (
+            SELECT R1.hicl_seqno
+            FROM RMEDMHL0_MED_HICLSEQNO_LINK R1
+            WHERE R1.med_concept_id_typ = 1
+              AND R1.med_concept_id = :allergenConceptID
+              AND MED_CONCEPT_HICL_SRC_CD = 0
+        )
+    )
+    ",
+            ['medid' => $_rx->data->medId, 'allergenConceptID' => $_allergen->data->damConceptId]
+        );
+
+        return !!count($matches);
+    }
+}
+if(!function_exists('drugAllergyGroupAllergenVsSingleRx')) {
+    function drugAllergyGroupAllergenVsSingleRx($_allergen, $_rx)
+    {
+
+        $matches = DB::connection('pgsql_fdb')->select("
+(
+    -- ingredients from medication
+    SELECT R1.related_hic_seqn as hic_seqn
+    FROM RHICHCR0_HIC_HIC_LINK R1
+             JOIN RHICD5_HIC_DESC R2 ON R1.related_hic_seqn = R2.hic_seqn
+    WHERE R1.hic_seqn IN (
+        SELECT S2.dam_alrgn_hic_seqn
+        FROM RMEDMHL0_MED_HICLSEQNO_LINK S1
+                 JOIN RDAMHHA0_HIC_HICL_ALG_LINK S2 ON S1.hicl_seqno = S2.hicl_seqno
+        WHERE S1.med_concept_id = :medid
+          AND S1.med_concept_id_typ = 3
+    )
+)
+INTERSECT
+(
+    -- ingredients from medication allergen
+    (
+        SELECT R1.hic_seqn as hic_seqn
+        FROM RDAMGHC0_HIC_ALRGN_GRP_LINK R1
+        WHERE R1.DAM_ALRGN_GRP = :allergenConceptID
+    )
+    UNION
+    (
+        SELECT distinct s1.hic_seqn
+        FROM RDAMXHC0_HIC_ALRGN_XSENSE_LINK S1
+        WHERE S1.dam_alrgn_xsense IN (
+            SELECT R1.dam_alrgn_xsense
+            FROM RDAMGX0_ALRGN_GRP_XSENSE_LINK R1
+                     JOIN RDAMCSD1_XSENSIT_ALLERGY_DESC R2 on R1.dam_alrgn_xsense = R2.dam_alrgn_xsense
+            WHERE R1.dam_alrgn_grp = :allergenConceptID
+              AND R2.dam_alrgn_xsense_status_cd = 0
+        )
+    )
+)
+",
+            ['medid' => $_rx->data->medId, 'allergenConceptID' => $_allergen->data->damConceptId]
+        );
+
+        return !!count($matches);
+    }
+}
+
+if(!function_exists('drug_drug_interaction_info')) {
+    function drug_drug_interaction_info($_drugs) {
+
+        if(count($_drugs) < 2) return "";
+
+        $leftIndex = 0;
+
+        $output = [];
+
+        for ($i=$leftIndex; $i<count($_drugs) - 1; $i++) {
+            for ($j=$i + 1; $j<count($_drugs); $j++) {
+                $output[] = drugDrugInteractionSinglePair($_drugs[$i], $_drugs[$j]);
+            }
+        }
+
+        $output = array_filter($output, function($_x) {
+            return !!$_x;
+        });
+
+        return implode("<br>", $output);
+    }
+}
+if(!function_exists('drugDrugInteractionSinglePair')) {
+    function drugDrugInteractionSinglePair($_rx1, $_rx2)
+    {
+
+        $output = [];
+
+        // get active ingredient DDI_CODEX values for drug 1 and 2
+        $rx1ActiveDdiCodex = getActiveDdiCodexFromGcnSeqNo($_rx1->data->gcnSeqno);
+        $rx2ActiveDdiCodex = getActiveDdiCodexFromGcnSeqNo($_rx2->data->gcnSeqno);
+        if (!$rx1ActiveDdiCodex || !$rx2ActiveDdiCodex || !count($rx1ActiveDdiCodex) || !count($rx2ActiveDdiCodex)) return "";
+
+        //        dump($rx1_DDI_CODEX);
+        //        dump($rx2_DDI_CODEX);
+
+        // get inactive ingredient DDI_CODEX values for drug 1 and 2
+        // to get this we need to first get the NDCs of the drugs
+        $rx1Ndc = getNdcFromMedId($_rx1->data->medId);
+        $rx2Ndc = getNdcFromMedId($_rx2->data->medId);
+
+        //        dump($rx1Ndc);
+        //        dump($rx2Ndc);
+
+        $rx1InactiveDdiCodex = getInactiveDdiCodexFromNdc($rx1Ndc);
+        $rx2InactiveDdiCodex = getInactiveDdiCodexFromNdc($rx2Ndc);
+        // if(!$rx1InactiveDdiCodex || !$rx2InactiveDdiCodex || !count($rx1InactiveDdiCodex) || !count($rx2InactiveDdiCodex)) return "";
+
+        //        dump($rx1InactiveDdiCodex);
+        //        dump($rx2InactiveDdiCodex);
+
+        // get ddi codex - monox pairs for drug 1 & 2
+        $rx1ActiveDdiCodexMonoxPairs = getDdiCodexMonoxPairs($rx1ActiveDdiCodex);
+        $rx1InactiveDdiCodexMonoxPairs = getDdiCodexMonoxPairs($rx1InactiveDdiCodex);
+        $rx2ActiveDdiCodexMonoxPairs = getDdiCodexMonoxPairs($rx2ActiveDdiCodex);
+        $rx2InactiveDdiCodexMonoxPairs = getDdiCodexMonoxPairs($rx2InactiveDdiCodex);
+
+        //        dump($rx1ActiveDdiCodexMonoxPairs);
+        //        dump($rx1InactiveDdiCodexMonoxPairs);
+        //        dump($rx2ActiveDdiCodexMonoxPairs);
+        //        dump($rx2InactiveDdiCodexMonoxPairs);
+
+        // compare 1-active to 2-active and 2-inactive
+        $activeCatches = [];
+        foreach ($rx1ActiveDdiCodexMonoxPairs as $compareLeft) {
+            foreach ($rx2ActiveDdiCodexMonoxPairs as $compareRight) {
+                if ($compareLeft->ddi_monox == $compareRight->ddi_monox && $compareLeft->ddi_codex != $compareRight->ddi_codex) {
+                    $activeCatches[] = $compareLeft->ddi_codex;
+                }
+            }
+            foreach ($rx2InactiveDdiCodexMonoxPairs as $compareRight) {
+                if ($compareLeft->ddi_monox == $compareRight->ddi_monox && $compareLeft->ddi_codex != $compareRight->ddi_codex) {
+                    $activeCatches[] = $compareLeft->ddi_codex;
+                }
+            }
+        }
+
+        // compare 1-inactive to 2-active and 2-inactive
+        $inactiveCatches = [];
+        foreach ($rx1InactiveDdiCodexMonoxPairs as $compareLeft) {
+            foreach ($rx2ActiveDdiCodexMonoxPairs as $compareRight) {
+                if ($compareLeft->ddi_monox == $compareRight->ddi_monox && $compareLeft->ddi_codex != $compareRight->ddi_codex) {
+                    $inactiveCatches[] = $compareLeft->ddi_codex;
+                }
+            }
+            foreach ($rx2InactiveDdiCodexMonoxPairs as $compareRight) {
+                if ($compareLeft->ddi_monox == $compareRight->ddi_monox && $compareLeft->ddi_codex != $compareRight->ddi_codex) {
+                    $inactiveCatches[] = $compareLeft->ddi_codex;
+                }
+            }
+        }
+
+        if (count($activeCatches)) {
+            $output[] = "<b>{$_rx2->data->name}</b> interacts with one or more active ingredients in <b>{$_rx1->data->name}</b>.";
+        }
+        if (count($inactiveCatches)) {
+            $output[] = "<b>{$_rx2->data->name}</b> interacts with one or more inactive ingredients in <b>{$_rx1->data->name}</b>.";
+        }
+
+        // TODO: find out and show the names of the actual ingredients causing interaction
+
+        return implode("<br>", $output);
+    }
+}
+if(!function_exists('getActiveDdiCodexFromGcnSeqNo')) {
+    function getActiveDdiCodexFromGcnSeqNo($_gcnSeqNo)
+    {
+        $ddiCodexArray = [];
+        $query = DB::connection('pgsql_fdb')->select("
+    SELECT r1.ddi_codex
+    FROM RADIMGC4_GCNSEQNO_LINK r1
+    WHERE r1.gcn_seqno = :gcnSeqNo
+                ",
+            ['gcnSeqNo' => $_gcnSeqNo]
+        );
+        if (count($query)) {
+            $ddiCodexArray = array_map(function ($_x) {
+                return $_x->ddi_codex;
+            }, $query);
+        }
+        return $ddiCodexArray;
+    }
+}
+if(!function_exists('getNdcFromMedId')) {
+    function getNdcFromMedId($_medId)
+    {
+        $ndcArray = [];
+        $query = DB::connection('pgsql_fdb')->select("
+    select ndc from rmindc1_ndc_medid where medid = :medId
+                ",
+            ['medId' => $_medId]
+        );
+        if (count($query)) {
+            $ndcArray = array_map(function ($_x) {
+                return $_x->ndc;
+            }, $query);
+        }
+        return $ndcArray;
+    }
+}
+if(!function_exists('getInactiveDdiCodexFromNdc')) {
+    function getInactiveDdiCodexFromNdc($_ndc)
+    {
+        $ddiCodexArray = [];
+        if(!count($_ndc)) return $ddiCodexArray;
+        $query = DB::connection('pgsql_fdb')->select("
+    SELECT distinct r1.ddi_codex
+    FROM RDDIMIN0_NDC_INACTV_DDIM_LINK r1
+    WHERE r1.ddi_ndc IN (" . implode(',', array_map(function ($_x) {
+                return "'" . $_x . "'";
+            }, $_ndc)) . ")
+                "
+        );
+        if (count($query)) {
+            $ddiCodexArray = array_map(function ($_x) {
+                return $_x->ddi_codex;
+            }, $query);
+        }
+        return $ddiCodexArray;
+    }
+}
+if(!function_exists('getDdiCodexMonoxPairs')) {
+    function getDdiCodexMonoxPairs($_ddiCodexArray)
+    {
+        $ddiCodexMonoxPairsArray = [];
+        if(!count($_ddiCodexArray)) return $ddiCodexMonoxPairsArray;
+        if (count($_ddiCodexArray)) {
+            $ddiCodexMonoxPairsArray = DB::connection('pgsql_fdb')->select("
+SELECT r1.ddi_codex, r1.ddi_monox
+FROM RADIMMA5_MSTR r1
+WHERE r1.ddi_codex IN (" . implode(',', array_map(function ($_x) {
+                    return "'" . $_x . "'";
+                }, $_ddiCodexArray)) . ")
+            "
+            );
+        }
+        return $ddiCodexMonoxPairsArray;
+    }
+}
+
+if(!function_exists('duplicate_therapy_info')) {
+    function duplicate_therapy_info($_drugs) {
+
+        $dptClasses = [];
+        foreach ($_drugs as $drug) {
+            $drug->dpt = getDptClassFromGcnSeqNo($drug->data->gcnSeqno);
+        }
+
+        $leftIndex = 0;
+        $matches = [];
+        for ($i = $leftIndex; $i < count($_drugs) - 1; $i++) {
+            for ($j = $i + 1; $j < count($_drugs); $j++) {
+                $compareResult = compareDPTs($_drugs[$i]->dpt, $_drugs[$j]->dpt);
+                foreach ($compareResult as $c) {
+                    $matches[] = "<b>{$_drugs[$i]->data->name}</b> and <b>{$_drugs[$j]->data->name}</b> both participate in the duplicate therapy class <b>{$c->dpt_class_desc}</b> (duplicates allowed: {$c->dpt_allowance})";
+                }
+            }
+        }
+
+        if(!count($matches)) return '';
+
+        return "<ol class='pl-0 ml-3 mb-0'>" . implode("", array_map(function ($_x) {
+                return "<li class='mb-1'>" . $_x . "</li>";
+            }, $matches)) . "</ol>";
+    }
+}
+
+if (!function_exists('getDptClassFromGcnSeqNo')) {
+    function getDptClassFromGcnSeqNo($_gcnSeqNo)
+    {
+        return DB::connection('pgsql_fdb')->select("
+    SELECT distinct r1.dpt_class_id, r2.dpt_allowance, r2.dpt_class_desc
+    FROM RDPTGC0_GCNSEQNO_LINK r1
+    JOIN RDPTCL0_CLASS_ID r2 on r1.dpt_class_id = r2.dpt_class_id
+    WHERE r1.gcn_seqno = :gcnSeqNo
+                ",
+            ['gcnSeqNo' => $_gcnSeqNo]
+        );
+    }
+}
+if (!function_exists('compareDPTs')) {
+    function compareDPTs($_dptArray1, $_dptArray2)
+    {
+        $output = [];
+        for ($i = 0; $i < count($_dptArray1); $i++) {
+            for ($j = 0; $j < count($_dptArray2); $j++) {
+                if ($_dptArray1[$i]->dpt_class_id == $_dptArray2[$j]->dpt_class_id) {
+                    $output[] = json_decode(json_encode([
+                        "dpt_allowance" => $_dptArray1[$i]->dpt_allowance,
+                        "dpt_class_desc" => $_dptArray1[$i]->dpt_class_desc
+                    ]));
+                }
+            }
+        }
+        return $output;
+    }
+}
+
+if(!function_exists('coadministration_info')) {
+    function coadministration_info($_drugs) {
+
+        if(count($_drugs) < 2) return "";
+
+        // collect gcn-seq-nos
+        $gcnSeqNos = [];
+        $rxMap = [];
+        foreach ($_drugs as $drug) {
+            if(@$drug->data && $drug->data->gcnSeqno) {
+                $gcnSeqNos[] = $drug->data->gcnSeqno;
+                $rxMap[$drug->data->gcnSeqno] = $drug->data->name;
+            }
+        }
+        if(!count($gcnSeqNos)) return $result;
+
+        $gcnSeqNos = implode(',', array_map(function($_x) {
+            return "'" . $_x . "'";
+        }, $gcnSeqNos));
+
+        $coadministration = DB::connection('pgsql_fdb')->select("
+SELECT distinct r1.coadmin_dosing_text
+FROM radige0_ddi_gcnseqno_except r1
+WHERE r1.side_a_gcn_seqno in ($gcnSeqNos) AND r1.side_b_gcn_seqno in ($gcnSeqNos)
+            "
+        );
+
+        if(!$coadministration || !count($coadministration)) return '';
+
+        return "<ol class='pl-0 ml-3 mb-0'>" . implode("", array_map(function ($_x) {
+                return "<li class='mb-1'>" . $_x->coadmin_dosing_text . "</li>";
+            }, $coadministration)) . "</ol>";
+
+        return $coadministration;
+    }
+}

+ 40 - 0
app/Helpers/helpers.php

@@ -272,6 +272,20 @@ if(!function_exists('friendly_date')) {
     }
 }
 
+if(!function_exists('friendly_date_month_year')) {
+    function friendly_date_month_year($value) {
+        if(!$value || empty($value)) return '';
+        try {
+            $result = strtotime($value);
+            $result = date("M Y", $result);
+            return $result;
+        }
+        catch (Exception $e) {
+            return $value;
+        }
+    }
+}
+
 if(!function_exists('friendlier_date')) {
     function friendlier_date($value) {
         if(!$value || empty($value)) return '';
@@ -603,3 +617,29 @@ if(!function_exists('minutes_to_hhmm')) {
         return $h . ':' . $m;
     }
 }
+if(!function_exists('vsValue')) {
+    function vsValue($_v, $patient = null, $_direct = false)
+    {
+        if ($_direct) {
+            return $_v ? $_v : '<span class="font-weight-normal text-info font-italic">empty</span>';
+        }
+        return @($patient->{$_v}) ? $patient->{$_v} : '<span class="font-weight-normal text-info font-italic">empty</span>';
+    }
+}
+if(!function_exists('vsElement')) {
+    function vsElement($_v, $type, $name, $patient)
+    {
+        return '<input type="' . $type . '" class="form-control form-control-sm min-width-unset rounded-0" ' .
+            'name="' . $name . '" ' .
+            'value="' . (@($patient->{$_v}) ? $patient->{$_v} : '') . '">';
+    }
+}
+
+if(!function_exists('vsRoElement')) {
+    function vsRoElement($_v, $type, $name, $patient)
+    {
+        return '<input type="' . $type . '" readonly class="form-control form-control-sm min-width-unset rounded-0" ' .
+            'name="' . $name . '" ' .
+            'value="' . (@($patient->{$_v}) ? $patient->{$_v} : '') . '">';
+    }
+}

+ 16 - 0
app/Http/Controllers/AppointmentController.php

@@ -22,6 +22,12 @@ class AppointmentController extends Controller
 {
     public function events(Request $request)
     {
+
+        $performerPro = null;
+        if($this->performer && $this->performer->pro) {
+            $performerPro = $this->performer->pro;
+        }
+
         if(empty($request->get('proIds'))) {
             $proIds = [];
         }
@@ -39,6 +45,16 @@ class AppointmentController extends Controller
             ::where('start_time', '>=', $start)
             ->where('start_time', '<=', $end);
 
+        // for dna, limit to accessible pros
+        if($performerPro && $performerPro->isDefaultNA()) {
+            $teams = $performerPro->teamsWhereAssistant;
+            foreach ($teams as $team) {
+                if(!in_array($team->mcp_pro_id, $proIds)) {
+                    $proIds[] = $team->mcp_pro_id;
+                }
+            }
+        }
+
         if(count($proIds)) {
             $appointments = $appointments
                 ->where(function ($query) use ($proIds, $clientId) {

+ 0 - 1
app/Http/Controllers/Controller.php

@@ -90,6 +90,5 @@ class Controller extends BaseController
             'success' => false,
             'message' => $message
         ];
-        return null;
     }
 }

+ 726 - 0
app/Http/Controllers/FDBPGController.php

@@ -0,0 +1,726 @@
+<?php
+
+namespace App\Http\Controllers;
+
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\DB;
+
+class FDBPGController extends Controller
+{
+
+    public function rx(Request $request)
+    {
+        return view('app.fdb-pg.fdb-rx');
+    }
+
+    // 1. medication suggest
+    public function medSuggest(Request $request)
+    {
+        $term = $request->input('term') ? trim($request->input('term')) : '';
+        if (empty($term)) return '';
+        $matches = DB::connection('pgsql_fdb')->select(
+            "SELECT med_name_id, med_name FROM rminmid1_med_name WHERE med_status_cd = '0' AND med_name ILIKE :term ORDER BY med_name",
+            ['term' => '%' . $term . '%']
+        );
+        return view('app.fdb-pg.fdb-med-suggest', compact('matches'));
+    }
+
+    // 1.1 medication suggest (json response)
+    public function medSuggestJSON(Request $request)
+    {
+        $term = $request->input('term') ? trim($request->input('term')) : '';
+        if (empty($term)) return '';
+        $matches = DB::connection('pgsql_fdb')->select(
+            "SELECT med_name_id, med_name as text FROM rminmid1_med_name WHERE med_status_cd = '0' AND med_name ILIKE :term ORDER BY med_name",
+            ['term' => '%' . $term . '%']
+        );
+        return json_encode([
+            "success" => true,
+            "data" => $matches
+        ]);
+    }
+
+    // 2. routed meds from men name
+    public function routedMeds(Request $request)
+    {
+        $medNameID = $request->input('med-name-id') ? trim($request->input('med-name-id')) : '';
+        if (empty($medNameID)) return '';
+        $matches = DB::connection('pgsql_fdb')->select(
+            "SELECT routed_med_id, med_routed_med_id_desc FROM rmirmid1_routed_med WHERE med_status_cd = '0' AND med_name_id = :medNameID ORDER BY med_routed_med_id_desc",
+            ['medNameID' => $medNameID]
+        );
+        return json_encode($matches);
+    }
+
+    // 3. routed dosage from routed med
+    public function routedDosages(Request $request)
+    {
+        $routedMedID = $request->input('routed-med-id') ? trim($request->input('routed-med-id')) : '';
+        if (empty($routedMedID)) return '';
+        $matches = DB::connection('pgsql_fdb')->select(
+            "SELECT routed_dosage_form_med_id, med_routed_df_med_id_desc FROM rmidfid1_routed_dose_form_med WHERE med_status_cd = '0' AND routed_med_id = :routedMedID ORDER BY med_routed_df_med_id_desc",
+            ['routedMedID' => $routedMedID]
+        );
+        return json_encode($matches);
+    }
+
+    // 4. strengths from routed med
+    public function meds(Request $request)
+    {
+        $dosageFormMedId = $request->input('dosage-form-med-id') ? trim($request->input('dosage-form-med-id')) : '';
+        if (empty($dosageFormMedId)) return '';
+        $matches = DB::connection('pgsql_fdb')->select(
+            "SELECT medid, med_medid_desc, gcn_seqno FROM rmiid1_med WHERE med_status_cd = '0' AND routed_dosage_form_med_id = :dosageFormMedId ORDER BY med_medid_desc",
+            ['dosageFormMedId' => $dosageFormMedId]
+        );
+        return json_encode($matches);
+    }
+
+    // ** med suggest V2 ** //
+    public function medSuggestV2JSON(Request $request)
+    {
+        $term = $request->input('term') ? trim($request->input('term')) : '';
+        if (empty($term)) return '';
+        $matches = DB::connection('pgsql_fdb')->select("
+SELECT r_med.medid,
+       r_med.med_medid_desc as text,
+       r_med.gcn_seqno,
+       r_dosage_form.routed_dosage_form_med_id,
+       r_route.routed_med_id
+FROM rmiid1_med r_med
+         JOIN rmidfid1_routed_dose_form_med r_dosage_form
+              ON r_med.routed_dosage_form_med_id = r_dosage_form.routed_dosage_form_med_id
+         JOIN rmirmid1_routed_med r_route ON r_dosage_form.routed_med_id = r_route.routed_med_id
+WHERE r_med.med_status_cd = '0'
+  AND r_med.med_medid_desc ILIKE :term
+ORDER BY r_route.med_routed_med_id_desc, r_med.med_medid_desc",
+            ['term' => '%' . $term . '%']
+        );
+        return json_encode([
+            "success" => true,
+            "data" => $matches
+        ]);
+    }
+
+
+    // side effects for a given rx
+    public function sideEffects(Request $request)
+    {
+        $gcnSeqNo = $request->input('gcn-seq-no') ? trim($request->input('gcn-seq-no')) : '';
+        if (empty($gcnSeqNo)) return '';
+        $sides = DB::connection('pgsql_fdb')->select("
+SELECT r1.side, sm.side_freq, sm.side_sev, sm.dxid, dx.dxid_desc56
+FROM rsidegc0_gcnseqno_link r1
+    JOIN rsidema3_mstr sm ON r1.side = sm.side
+    JOIN rfmldx0_dxid dx ON sm.dxid = dx.dxid
+WHERE r1.gcn_seqno = :gcnSeqNo
+ORDER BY sm.side_sev DESC, sm.side_freq ASC
+            ",
+            ['gcnSeqNo' => $gcnSeqNo]
+        );
+        return view('app.fdb-pg.fdb-side-effects', compact('sides'));
+    }
+
+    // ger prec for a given rx
+    public function geriatricPrecautions(Request $request)
+    {
+        $gcnSeqNo = $request->input('gcn-seq-no') ? trim($request->input('gcn-seq-no')) : '';
+        if (empty($gcnSeqNo)) return '';
+        $precautions = DB::connection('pgsql_fdb')->select("
+SELECT r1.geri_code, gm.geri_sl, gm.geri_desc, gm.geri_narrative
+FROM rgerigc0_geri_gcnseqno_link r1
+    JOIN rgerima1_geri_mstr gm ON r1.geri_code = gm.geri_code
+WHERE r1.gcn_seqno = :gcnSeqNo
+ORDER BY gm.geri_desc
+            ",
+            ['gcnSeqNo' => $gcnSeqNo]
+        );
+        return view('app.fdb-pg.fdb-geriatric-precautions', compact('precautions'));
+    }
+
+    // indication of a given rx
+    public function indications(Request $request)
+    {
+        $gcnSeqNo = $request->input('gcn-seq-no') ? trim($request->input('gcn-seq-no')) : '';
+        if (empty($gcnSeqNo)) return '';
+        $indications = DB::connection('pgsql_fdb')->select("
+SELECT r1.indcts, r2.indcts_sn, r2.indcts_lbl, r2.dxid, r2.proxy_ind, r3.dxid_desc56
+FROM rindmgc0_indcts_gcnseqno_link r1
+    JOIN rindmma2_indcts_mstr r2 ON r1.indcts = r2.indcts
+    JOIN rfmldx0_dxid r3 ON r2.dxid = r3.dxid
+WHERE r1.gcn_seqno = :gcnSeqNo
+ORDER BY r3.dxid_desc56
+            ",
+            ['gcnSeqNo' => $gcnSeqNo]
+        );
+        return view('app.fdb-pg.fdb-indications', compact('indications'));
+    }
+
+    // contra-indications of a given rx
+    public function contraindications(Request $request)
+    {
+        $routedMedID = $request->input('routed-med-id') ? trim($request->input('routed-med-id')) : '';
+        if (empty($routedMedID)) return '';
+        $contraindications = DB::connection('pgsql_fdb')->select("
+SELECT r1.ddxcn, r2.dxid, r2.ddxcn_sl, r3.dxid_desc56
+FROM rddcmrm0_routed_med_link r1
+    JOIN rddcmma1_contra_mstr r2 ON r1.ddxcn = r2.ddxcn
+    JOIN rfmldx0_dxid r3 ON r2.dxid = r3.dxid
+WHERE r1.routed_med_id = :routedMedID
+ORDER BY r2.ddxcn_sl
+            ",
+            ['routedMedID' => $routedMedID]
+        );
+        return view('app.fdb-pg.fdb-contraindications', compact('contraindications'));
+    }
+
+    // dx suggest
+    public function dxSuggest(Request $request)
+    {
+        $term = $request->input('term') ? trim($request->input('term')) : '';
+        if (empty($term)) return '';
+        $matches = DB::connection('pgsql_fdb')->select("
+SELECT distinct(r1.dxid), r1.dxid_desc56
+FROM rfmldx0_dxid r1
+JOIN rfmlsyn0_dxid_syn r2 ON r1.dxid = r2.dxid
+WHERE (r1.dxid_desc56 ILIKE :term OR r1.dxid_desc100 ILIKE :term OR r2.dxid_syn_desc56 ILIKE :term OR r2.dxid_syn_desc100 ILIKE :term)
+ORDER BY r1.dxid_desc56
+",
+            ['term' => '%' . $term . '%']
+        );
+        return view('app.fdb-pg.fdb-dx-suggest', compact('matches'));
+    }
+
+    public function dxSuggestJSON(Request $request)
+    {
+        $term = $request->input('term') ? trim($request->input('term')) : '';
+        if (empty($term)) return '';
+        $matches = DB::connection('pgsql_fdb')->select("
+SELECT distinct(r1.dxid), r1.dxid_desc56 as text
+FROM rfmldx0_dxid r1
+JOIN rfmlsyn0_dxid_syn r2 ON r1.dxid = r2.dxid
+WHERE (r1.dxid_desc56 ILIKE :term OR r1.dxid_desc100 ILIKE :term OR r2.dxid_syn_desc56 ILIKE :term OR r2.dxid_syn_desc100 ILIKE :term)
+ORDER BY r1.dxid_desc56
+",
+            ['term' => '%' . $term . '%']
+        );
+        return response()->json(['success'=>true, 'data'=>$matches]);
+    }
+
+    public function dxICDsForDxID(Request $request) {
+        $matches = DB::connection('pgsql_fdb')->select("
+select r1.search_icd_cd, r1.icd_cd_type, r2.icd_desc
+from RFMLISR1_ICD_SEARCH r1
+left join RFMLINM1_ICD_DESC r2 on r1.search_icd_cd = r2.icd_cd
+where r1.related_dxid = :dxid
+  and (/*r1.icd_cd_type = '01' or */r1.icd_cd_type = '05')
+  and r1.fml_clin_code = '01'
+  /*and fml_nav_code = '01'*/
+",
+            ['dxid' => $request->input('dxid')]
+        );
+        return response()->json($matches);
+    }
+
+    // allergy suggest
+    public function allergySuggest(Request $request)
+    {
+        $term = $request->input('term') ? trim($request->input('term')) : '';
+        if (empty($term)) return '';
+        $matches = DB::connection('pgsql_fdb')->select("
+SELECT r1.dam_concept_id, r1.dam_concept_id_typ, r1.dam_concept_id_desc
+FROM rdamca0_concept r1
+WHERE (r1.dam_concept_id_desc ILIKE :term)
+ORDER BY r1.dam_concept_id_desc
+",
+            ['term' => '%' . $term . '%']
+        );
+        return view('app.fdb-pg.fdb-allergy-suggest', compact('matches'));
+    }
+
+    // allergy suggest (json response)
+    public function allergySuggestJSON(Request $request)
+    {
+        $term = $request->input('term') ? trim($request->input('term')) : '';
+        if (empty($term)) return '';
+        $matches = DB::connection('pgsql_fdb')->select("
+SELECT r1.dam_concept_id, r1.dam_concept_id_typ, r1.dam_concept_id_desc as text
+FROM rdamca0_concept r1
+WHERE (r1.dam_concept_id_desc ILIKE :term)
+ORDER BY r1.dam_concept_id_desc
+",
+            ['term' => '%' . $term . '%']
+        );
+        return json_encode([
+            "success" => true,
+            "data" => $matches
+        ]);
+    }
+
+    // drug <-> allergy match making
+    public function drugAllergies(Request $request) {
+
+        // override
+        if($request->input('test')) {
+            $x = new \stdClass();
+            $x->allergen = 'Pollen';
+            $x->dam_concept_id_typ = 6;
+            $allergies = [$x];
+            $y = new \stdClass();
+            $y->rx = 'Brufen';
+            $rx = [$y];
+        }
+        else {
+            $input = json_decode($request->input('data'));
+            $allergies = $input->allergies;
+            $rx = $input->rx;
+        }
+
+        $output = [];
+
+        /*
+        for each allergy
+            if dam_concept_id_typ = 1 // allergen-group-id
+                // https://docs.fdbhealth.com/display/MKDOCUS/Screening+an+NDC+for+a+DAM_ALRGN_GRP+Allergen+-+Illustration+of+Scenario+C
+                ...
+            elseif dam_concept_id_typ = 2 // medication-name-id
+                // https://docs.fdbhealth.com/display/MKDOCUS/Screening+an+NDC+for+a+MED_NAME_ID+Allergen+-+Illustration+of+Scenario+B
+                ...
+            elseif dam_concept_id_typ = 6 // base-ingredient-id
+                // https://docs.fdbhealth.com/display/MKDOCUS/Screening+an+NDC+for+an+Ingredient+Allergen+-+Illustration+of+Scenario+A
+                ...
+            endif
+        endfor
+        */
+
+        foreach ($allergies as $allergy) {
+            foreach ($rx as $rxItem) {
+                if($allergy->dam_concept_id_typ == 6) { // ingredient
+                    if ($this->drugAllergyIngredientAllergenVsSingleRx($allergy, $rxItem)) {
+                        $output[] = "<b>{$rxItem->rx}</b> can cause allergic reactions since the patient is allergic to <b>{$allergy->allergen}</b>.";
+                    }
+                }
+                else if($allergy->dam_concept_id_typ == 2) { // medication
+                    if ($this->drugAllergyMedicationAllergenVsSingleRx($allergy, $rxItem)) {
+                        $output[] = "<b>{$rxItem->rx}</b> can cause allergic reactions since the patient is allergic to <b>{$allergy->allergen}</b>.";
+                    }
+                }
+                else if($allergy->dam_concept_id_typ == 1) { // allergen group
+                    if ($this->drugAllergyGroupAllergenVsSingleRx($allergy, $rxItem)) {
+                        $output[] = "<b>{$rxItem->rx}</b> can cause allergic reactions since the patient is allergic to <b>{$allergy->allergen}</b>.";
+                    }
+                }
+            }
+        }
+
+        return implode("<br>", $output);
+
+    }
+
+        private function drugAllergyIngredientAllergenVsSingleRx($_allergen, $_rx) {
+
+            $matches = DB::connection('pgsql_fdb')->select("
+    (
+        -- ingredients from medication
+        SELECT R1.related_hic_seqn as hic_seqn, R2.hic_desc
+        FROM RHICHCR0_HIC_HIC_LINK R1
+                 JOIN RHICD5_HIC_DESC R2 ON R1.related_hic_seqn = R2.hic_seqn
+        WHERE R1.hic_seqn IN (
+            SELECT S2.dam_alrgn_hic_seqn
+            FROM RMEDMHL0_MED_HICLSEQNO_LINK S1
+                     JOIN RDAMHHA0_HIC_HICL_ALG_LINK S2 ON S1.hicl_seqno = S2.hicl_seqno
+            WHERE S1.med_concept_id = :medid
+              AND S1.med_concept_id_typ = 3
+        )
+    )
+    INTERSECT
+    (
+        -- all ingredients directly and related from allergens
+        (
+            SELECT R1.related_hic_seqn as hic_seqn, R2.hic_desc
+            FROM RHICHCR0_HIC_HIC_LINK R1
+                     JOIN RHICD5_HIC_DESC R2 ON R1.related_hic_seqn = R2.hic_seqn
+            WHERE R1.hic_seqn = :allergenConceptID
+        )
+        UNION
+        -- all ingredients via related dam allergen groups
+        (
+            SELECT r3.hic_seqn, r4.hic_desc
+            FROM RDAMGHC0_HIC_ALRGN_GRP_LINK R1
+                     JOIN rdamagd1_alrgn_grp_desc R2 on R1.dam_alrgn_grp = R2.dam_alrgn_grp
+                     JOIN RDAMGHC0_HIC_ALRGN_GRP_LINK R3 on R1.dam_alrgn_grp = R3.dam_alrgn_grp
+                     JOIN RHICD5_HIC_DESC R4 on r3.hic_seqn = r4.hic_seqn
+            WHERE R1.hic_seqn = :allergenConceptID
+              AND R2.dam_alrgn_grp_status_cd = 0
+            ORDER BY r3.hic_seqn
+        )
+    )
+    ",
+                ['medid' => $_rx->medid, 'allergenConceptID' => $_allergen->dam_concept_id]
+            );
+
+            return !!count($matches);
+        }
+
+        private function drugAllergyMedicationAllergenVsSingleRx($_allergen, $_rx) {
+
+            $matches = DB::connection('pgsql_fdb')->select("
+    (
+        -- ingredients from medication
+        SELECT R1.related_hic_seqn as hic_seqn
+        FROM RHICHCR0_HIC_HIC_LINK R1
+                 JOIN RHICD5_HIC_DESC R2 ON R1.related_hic_seqn = R2.hic_seqn
+        WHERE R1.hic_seqn IN (
+            SELECT S2.dam_alrgn_hic_seqn
+            FROM RMEDMHL0_MED_HICLSEQNO_LINK S1
+                     JOIN RDAMHHA0_HIC_HICL_ALG_LINK S2 ON S1.hicl_seqno = S2.hicl_seqno
+            WHERE S1.med_concept_id = :medid
+              AND S1.med_concept_id_typ = 3
+        )
+    )
+    INTERSECT
+    (
+        -- all ingredients directly and related from allergens
+        SELECT R1.dam_alrgn_hic_seqn as hic_seqn
+        FROM RDAMHHA0_HIC_HICL_ALG_LINK R1
+        WHERE R1.hicl_seqno IN (
+            SELECT R1.hicl_seqno
+            FROM RMEDMHL0_MED_HICLSEQNO_LINK R1
+            WHERE R1.med_concept_id_typ = 1
+              AND R1.med_concept_id = :allergenConceptID
+              AND MED_CONCEPT_HICL_SRC_CD = 0
+        )
+    )
+    ",
+                ['medid' => $_rx->medid, 'allergenConceptID' => $_allergen->dam_concept_id]
+            );
+
+            return !!count($matches);
+        }
+
+        private function drugAllergyGroupAllergenVsSingleRx($_allergen, $_rx) {
+
+        $matches = DB::connection('pgsql_fdb')->select("
+(
+    -- ingredients from medication
+    SELECT R1.related_hic_seqn as hic_seqn
+    FROM RHICHCR0_HIC_HIC_LINK R1
+             JOIN RHICD5_HIC_DESC R2 ON R1.related_hic_seqn = R2.hic_seqn
+    WHERE R1.hic_seqn IN (
+        SELECT S2.dam_alrgn_hic_seqn
+        FROM RMEDMHL0_MED_HICLSEQNO_LINK S1
+                 JOIN RDAMHHA0_HIC_HICL_ALG_LINK S2 ON S1.hicl_seqno = S2.hicl_seqno
+        WHERE S1.med_concept_id = :medid
+          AND S1.med_concept_id_typ = 3
+    )
+)
+INTERSECT
+(
+    -- ingredients from medication allergen
+    (
+        SELECT R1.hic_seqn as hic_seqn
+        FROM RDAMGHC0_HIC_ALRGN_GRP_LINK R1
+        WHERE R1.DAM_ALRGN_GRP = :allergenConceptID
+    )
+    UNION
+    (
+        SELECT distinct s1.hic_seqn
+        FROM RDAMXHC0_HIC_ALRGN_XSENSE_LINK S1
+        WHERE S1.dam_alrgn_xsense IN (
+            SELECT R1.dam_alrgn_xsense
+            FROM RDAMGX0_ALRGN_GRP_XSENSE_LINK R1
+                     JOIN RDAMCSD1_XSENSIT_ALLERGY_DESC R2 on R1.dam_alrgn_xsense = R2.dam_alrgn_xsense
+            WHERE R1.dam_alrgn_grp = :allergenConceptID
+              AND R2.dam_alrgn_xsense_status_cd = 0
+        )
+    )
+)
+",
+            ['medid' => $_rx->medid, 'allergenConceptID' => $_allergen->dam_concept_id]
+        );
+
+        return !!count($matches);
+    }
+
+    // drug <-> drug match making
+    public function drugDrugInteraction(Request $request) {
+
+        if($request->input('test')) {
+            // override
+            $rx = json_decode(json_encode([
+                [
+                    "gcn_seqno" => "45190",
+                    "med_name_id" => "18604",
+                    "medid" => "234539",
+                    "routed_dosage_form_med_id" => "95130",
+                    "routed_med_id" => "19876",
+                    "rx" => "Zyprexa Zydis",
+                ],
+                [
+                    "gcn_seqno" => "49853",
+                    "med_name_id" => "26164",
+                    "medid" => "400058",
+                    "routed_dosage_form_med_id" => "36194",
+                    "routed_med_id" => "32562",
+                    "rx" => "Orfadin",
+                ],
+            ]));
+        }
+        else {
+            $input = json_decode($request->input('data'));
+            $rx = $input->rx;
+        }
+
+        if(count($rx) < 2) return "";
+
+        $leftIndex = 0;
+
+        $output = [];
+
+        for ($i=$leftIndex; $i<count($rx) - 1; $i++) {
+            for ($j=$i + 1; $j<count($rx); $j++) {
+                $output[] = $this->drugDrugInteractionSinglePair($rx[$i], $rx[$j]);
+            }
+        }
+
+        $output = array_filter($output, function($_x) {
+            return !!$_x;
+        });
+
+        return implode("<br>", $output);
+    }
+
+        private function drugDrugInteractionSinglePair($_rx1, $_rx2) {
+
+            $output = [];
+
+            // get active ingredient DDI_CODEX values for drug 1 and 2
+            $rx1ActiveDdiCodex = $this->getActiveDdiCodexFromGcnSeqNo($_rx1->gcn_seqno);
+            $rx2ActiveDdiCodex = $this->getActiveDdiCodexFromGcnSeqNo($_rx2->gcn_seqno);
+            if(!$rx1ActiveDdiCodex || !$rx2ActiveDdiCodex || !count($rx1ActiveDdiCodex) || !count($rx2ActiveDdiCodex)) return "";
+
+    //        dump($rx1_DDI_CODEX);
+    //        dump($rx2_DDI_CODEX);
+
+            // get inactive ingredient DDI_CODEX values for drug 1 and 2
+            // to get this we need to first get the NDCs of the drugs
+            $rx1Ndc = $this->getNdcFromMedId($_rx1->medid);
+            $rx2Ndc = $this->getNdcFromMedId($_rx2->medid);
+
+    //        dump($rx1Ndc);
+    //        dump($rx2Ndc);
+
+            $rx1InactiveDdiCodex = $this->getInactiveDdiCodexFromNdc($rx1Ndc);
+            $rx2InactiveDdiCodex = $this->getInactiveDdiCodexFromNdc($rx2Ndc);
+            // if(!$rx1InactiveDdiCodex || !$rx2InactiveDdiCodex || !count($rx1InactiveDdiCodex) || !count($rx2InactiveDdiCodex)) return "";
+
+    //        dump($rx1InactiveDdiCodex);
+    //        dump($rx2InactiveDdiCodex);
+
+            // get ddi codex - monox pairs for drug 1 & 2
+            $rx1ActiveDdiCodexMonoxPairs = $this->getDdiCodexMonoxPairs($rx1ActiveDdiCodex);
+            $rx1InactiveDdiCodexMonoxPairs = $this->getDdiCodexMonoxPairs($rx1InactiveDdiCodex);
+            $rx2ActiveDdiCodexMonoxPairs = $this->getDdiCodexMonoxPairs($rx2ActiveDdiCodex);
+            $rx2InactiveDdiCodexMonoxPairs = $this->getDdiCodexMonoxPairs($rx2InactiveDdiCodex);
+
+    //        dump($rx1ActiveDdiCodexMonoxPairs);
+    //        dump($rx1InactiveDdiCodexMonoxPairs);
+    //        dump($rx2ActiveDdiCodexMonoxPairs);
+    //        dump($rx2InactiveDdiCodexMonoxPairs);
+
+            // compare 1-active to 2-active and 2-inactive
+            $activeCatches = [];
+            foreach ($rx1ActiveDdiCodexMonoxPairs as $compareLeft) {
+                foreach ($rx2ActiveDdiCodexMonoxPairs as $compareRight) {
+                    if($compareLeft->ddi_monox == $compareRight->ddi_monox && $compareLeft->ddi_codex != $compareRight->ddi_codex) {
+                        $activeCatches[] = $compareLeft->ddi_codex;
+                    }
+                }
+                foreach ($rx2InactiveDdiCodexMonoxPairs as $compareRight) {
+                    if($compareLeft->ddi_monox == $compareRight->ddi_monox && $compareLeft->ddi_codex != $compareRight->ddi_codex) {
+                        $activeCatches[] = $compareLeft->ddi_codex;
+                    }
+                }
+            }
+
+            // compare 1-inactive to 2-active and 2-inactive
+            $inactiveCatches = [];
+            foreach ($rx1InactiveDdiCodexMonoxPairs as $compareLeft) {
+                foreach ($rx2ActiveDdiCodexMonoxPairs as $compareRight) {
+                    if($compareLeft->ddi_monox == $compareRight->ddi_monox && $compareLeft->ddi_codex != $compareRight->ddi_codex) {
+                        $inactiveCatches[] = $compareLeft->ddi_codex;
+                    }
+                }
+                foreach ($rx2InactiveDdiCodexMonoxPairs as $compareRight) {
+                    if($compareLeft->ddi_monox == $compareRight->ddi_monox && $compareLeft->ddi_codex != $compareRight->ddi_codex) {
+                        $inactiveCatches[] = $compareLeft->ddi_codex;
+                    }
+                }
+            }
+
+            if(count($activeCatches)) {
+                $output[] = "<b>{$_rx2->rx}</b> interacts with one or more active ingredients in <b>{$_rx1->rx}</b>.";
+            }
+            if(count($inactiveCatches)) {
+                $output[] = "<b>{$_rx2->rx}</b> interacts with one or more inactive ingredients in <b>{$_rx1->rx}</b>.";
+            }
+
+            // TODO: find out and show the names of the actual ingredients causing interaction
+
+            return implode("<br>", $output);
+        }
+
+        private function getActiveDdiCodexFromGcnSeqNo($_gcnSeqNo) {
+            $ddiCodexArray = [];
+            $query = DB::connection('pgsql_fdb')->select("
+    SELECT r1.ddi_codex
+    FROM RADIMGC4_GCNSEQNO_LINK r1
+    WHERE r1.gcn_seqno = :gcnSeqNo
+                ",
+                ['gcnSeqNo' => $_gcnSeqNo]
+            );
+            if(count($query)) {
+                $ddiCodexArray = array_map(function($_x) {
+                    return $_x->ddi_codex;
+                }, $query);
+            }
+            return $ddiCodexArray;
+        }
+
+        private function getNdcFromMedId($_medId) {
+            $ndcArray = [];
+            $query = DB::connection('pgsql_fdb')->select("
+    select ndc from rmindc1_ndc_medid where medid = :medId
+                ",
+                ['medId' => $_medId]
+            );
+            if(count($query)) {
+                $ndcArray = array_map(function($_x) {
+                    return $_x->ndc;
+                }, $query);
+            }
+            return $ndcArray;
+        }
+
+        private function getInactiveDdiCodexFromNdc($_ndc) {
+            $ddiCodexArray = [];
+            $query = DB::connection('pgsql_fdb')->select("
+    SELECT distinct r1.ddi_codex
+    FROM RDDIMIN0_NDC_INACTV_DDIM_LINK r1
+    WHERE r1.ddi_ndc IN (" . implode(',', array_map(function($_x) {return "'" . $_x . "'";}, $_ndc)) . ")
+                "
+            );
+            if(count($query)) {
+                $ddiCodexArray = array_map(function($_x) {
+                    return $_x->ddi_codex;
+                }, $query);
+            }
+            return $ddiCodexArray;
+        }
+
+        private function getDdiCodexMonoxPairs($_ddiCodexArray) {
+        $ddiCodexMonoxPairsArray = [];
+        if(count($_ddiCodexArray)) {
+            $ddiCodexMonoxPairsArray = DB::connection('pgsql_fdb')->select("
+SELECT r1.ddi_codex, r1.ddi_monox
+FROM RADIMMA5_MSTR r1
+WHERE r1.ddi_codex IN (" . implode(',', array_map(function($_x) {return "'" . $_x . "'";}, $_ddiCodexArray)) . ")
+            "
+            );
+        }
+        return $ddiCodexMonoxPairsArray;
+    }
+
+    // drug <-> drug coadministration notes
+    public function drugCoadministration(Request $request) {
+        $gcnSeqnos = $request->input('gcn-seqnos') ? trim($request->input('gcn-seqnos')) : '';
+        if (empty($gcnSeqnos)) return '';
+        //$gcnSeqnos = explode(",", $gcnSeqnos);
+
+        $coadministration = DB::connection('pgsql_fdb')->select("
+SELECT distinct r1.coadmin_dosing_text
+FROM radige0_ddi_gcnseqno_except r1
+WHERE r1.side_a_gcn_seqno in ($gcnSeqnos) AND r1.side_b_gcn_seqno in ($gcnSeqnos)
+            "
+        );
+        return view('app.fdb-pg.fdb-coadministration', compact('coadministration'));
+    }
+
+    // duplicate therapy indications
+    public function duplicateTherapy(Request $request) {
+
+        if($request->input('test')) {
+            // override
+            $rx = json_decode(json_encode([
+                [
+                    "gcn_seqno" => "4376",
+                    "med_name_id" => "1076",
+                    "medid" => "172480",
+                    "routed_dosage_form_med_id" => "5870",
+                    "routed_med_id" => "1082",
+                    "rx" => "aspirin 325",
+                ],
+                [
+                    "gcn_seqno" => "4377",
+                    "med_name_id" => "1076",
+                    "medid" => "216092",
+                    "routed_dosage_form_med_id" => "5870",
+                    "routed_med_id" => "1082",
+                    "rx" => "aspirin 500",
+                ],
+            ]));
+        }
+        else {
+            $input = json_decode($request->input('data'));
+            $rx = $input->rx;
+        }
+
+        $dptClasses = [];
+        foreach ($rx as $rxItem) {
+            $rxItem->dpt = $this->getDptClassFromGcnSeqNo($rxItem->gcn_seqno);
+        }
+
+        // dd($rx);
+
+        $leftIndex = 0;
+        $matches = [];
+        for ($i=$leftIndex; $i<count($rx) - 1; $i++) {
+            for ($j=$i + 1; $j<count($rx); $j++) {
+                $compareResult = $this->compareDPTs($rx[$i]->dpt, $rx[$j]->dpt);
+                foreach ($compareResult as $c) {
+                    $matches[] = "<b>{$rx[$i]->rx}</b> and <b>{$rx[$j]->rx}</b> both participate in the duplicate therapy class <b>{$c->dpt_class_desc}</b> (duplicates allowed: {$c->dpt_allowance})";
+                }
+            }
+        }
+
+        return "<ol class='pl-0 ml-3'>" . implode("", array_map(function($_x) {
+                return "<li class='mb-2'>" . $_x . "</li>";
+            }, $matches)) . "</ol>";
+    }
+
+        private function getDptClassFromGcnSeqNo($_gcnSeqNo) {
+            return DB::connection('pgsql_fdb')->select("
+    SELECT distinct r1.dpt_class_id, r2.dpt_allowance, r2.dpt_class_desc
+    FROM RDPTGC0_GCNSEQNO_LINK r1
+    JOIN RDPTCL0_CLASS_ID r2 on r1.dpt_class_id = r2.dpt_class_id
+    WHERE r1.gcn_seqno = :gcnSeqNo
+                ",
+                ['gcnSeqNo' => $_gcnSeqNo]
+            );
+        }
+
+        private function compareDPTs($_dptArray1, $_dptArray2) {
+        $output = [];
+        for ($i=0; $i<count($_dptArray1); $i++) {
+            for ($j=0; $j<count($_dptArray2); $j++) {
+                if($_dptArray1[$i]->dpt_class_id == $_dptArray2[$j]->dpt_class_id) {
+                    $output[] = json_decode(json_encode([
+                        "dpt_allowance" => $_dptArray1[$i]->dpt_allowance,
+                        "dpt_class_desc" => $_dptArray1[$i]->dpt_class_desc
+                    ]));
+                }
+            }
+        }
+        return $output;
+    }
+}

+ 161 - 28
app/Http/Controllers/HomeController.php

@@ -4,6 +4,7 @@ namespace App\Http\Controllers;
 
 use App\Lib\Backend;
 use App\Models\Appointment;
+use App\Models\AppointmentConfirmationDecision;
 use App\Models\AppSession;
 use App\Models\ClientMemo;
 use App\Models\ClientProChange;
@@ -231,13 +232,23 @@ class HomeController extends Controller
 
         $keyNumbers['pendingBillsToSign'] = $pendingBillsToSign;
 
-        $pendingNotesToSign = Note::where(function ($query) use ($performerProID) {
-            $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_cancelled', false);;
-        })
+        $pendingNotesToSign = Note
+            ::where(function ($query) use ($performerProID) {
+                $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_cancelled', false);
+            })
             ->orWhere(function ($query) use ($performerProID) {
-                $query->where('ally_pro_id', $performerProID)->where('is_signed_by_ally', false)->where('is_cancelled', false);;
-            })->count();
-            $keyNumbers['pendingNotesToSign'] = $pendingNotesToSign;
+                $query->where('ally_pro_id', $performerProID)->where('is_signed_by_ally', false)->where('is_cancelled', false);
+            })
+            ->count();
+        $keyNumbers['pendingNotesToSign'] = $pendingNotesToSign;
+
+        // notes pending mcp sign (applicable to dnas only)
+        $pendingNotesToSignMCP = Note
+            ::where(function ($query) use ($performerProID) {
+                $query->where('ally_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_cancelled', false);
+            })
+            ->count();
+        $keyNumbers['$pendingNotesToSignMCP'] = $pendingNotesToSignMCP;
 
         $pendingNotesToSignAllySigned = Note::where(function ($query) use ($performerProID) {
             $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_signed_by_ally', true)->where('is_cancelled', false);;
@@ -246,7 +257,7 @@ class HomeController extends Controller
 
 
         $signedNotesWithoutBills = Note::where(function ($query) use ($performerProID) {
-            $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', true)->where('is_cancelled', false);;
+            $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', true)->where('is_cancelled', false);
         })->whereDoesntHave('bills')->count();
 
         $keyNumbers['signedNotesWithoutBills'] = $signedNotesWithoutBills;
@@ -393,6 +404,40 @@ class HomeController extends Controller
             ->whereNull('current_client_pro_change_decision_id')
             ->get();
 
+        $proApptUpdates = AppointmentConfirmationDecision
+            ::select('appointment_confirmation_decision.uid', 'client.name_first', 'client.name_last', 'appointment.start_time')
+            ->rightJoin('appointment', 'appointment.id', '=', 'appointment_confirmation_decision.appointment_id')
+            ->rightJoin('client', 'client.id', '=', 'appointment.client_id')
+            ->where('appointment_confirmation_decision.was_acknowledged_by_appointment_pro', false)
+            ->where('appointment.status', '!=', 'CREATED')
+            ->where('appointment.status', '!=', 'COMPLETED')
+            ->where('appointment.status', '!=', 'ABANDONED')
+            ->where('appointment.pro_id', $performerProID)
+            ->where('client.mcp_pro_id', $performerProID)
+            ->orderBy('appointment.start_time', 'DESC')
+            ->get();
+
+        $naApptUpdates = AppointmentConfirmationDecision
+            ::select('appointment_confirmation_decision.uid', 'client.name_first', 'client.name_last', 'pro.name_first as pro_name_first', 'pro.name_last as pro_name_last', 'appointment.start_time')
+            ->rightJoin('appointment', 'appointment.id', '=', 'appointment_confirmation_decision.appointment_id')
+            ->rightJoin('client', 'client.id', '=', 'appointment.client_id')
+            ->rightJoin('pro', 'pro.id', '=', 'appointment.pro_id')
+            ->where('appointment_confirmation_decision.was_acknowledged_by_client_default_na', false)
+            ->where('appointment.status', '!=', 'CREATED')
+            ->where('appointment.status', '!=', 'COMPLETED')
+            ->where('appointment.status', '!=', 'ABANDONED')
+            ->where('client.default_na_pro_id', $performerProID)
+            ->orderBy('appointment.start_time', 'DESC')
+            ->get();
+
+//        $naApptUpdates = AppointmentConfirmationDecision
+//            ::join('appointment', 'appointment.id', '=', 'appointment_confirmation_decision.appointment_id')
+//            ->join('client', 'client.id', '=', 'appointment.client_id')
+//            ->where('client.default_na_pro_id', $performerProID)
+//            ->where('appointment_confirmation_decision.was_acknowledged_by_client_default_na', false)
+//            ->orderBy('appointment.start_time DESC')
+//            ->get();
+
         // unstamped client memos
         // for mcp
         $mcpClientMemos = DB::select(
@@ -427,11 +472,11 @@ WHERE
         note.ally_pro_id = :pro_id AND
         note.is_cancelled = FALSE AND
         (
-            SELECT count(bill.id) 
-            FROM bill 
-            WHERE 
-                  bill.is_cancelled = FALSE AND 
-                  bill.generic_pro_id = :pro_id AND 
+            SELECT count(bill.id)
+            FROM bill
+            WHERE
+                  bill.is_cancelled = FALSE AND
+                  bill.generic_pro_id = :pro_id AND
                   bill.note_id = note.id
         ) = 0
         "), ["pro_id" => $performerProID]);
@@ -524,12 +569,39 @@ WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$per
         // num measurements that need stamping
         $keyNumbers['measurementsToBeStamped'] = $this->performer()->pro->getUnstampedMeasurementsFromCurrentMonth(true, null, null);
 
+        if($performer->pro->pro_type === 'ADMIN') {
+
+            // patients without coverage information
+            $keyNumbers['patientsWithoutCoverageInformation'] = DB::select(DB::raw("
+SELECT count(DISTINCT (cl.id)) as cnt
+FROM client cl
+WHERE cl.shadow_pro_id IS NULL AND cl.latest_client_primary_coverage_id IS NULL -- no coverage record"
+            ))[0]->cnt;
+
+            // patients pending coverage verification
+            $keyNumbers['patientsPendingCoverageVerification'] = DB::select(DB::raw("
+SELECT count(DISTINCT (cl.id)) as cnt
+FROM client cl
+         LEFT JOIN client_primary_coverage cpc ON cl.latest_client_primary_coverage_id = cpc.id
+WHERE cl.shadow_pro_id IS NULL 
+    AND (cl.latest_client_primary_coverage_id IS NOT NULL -- coverage exists, but status is null or unknown
+    AND (
+               (cpc.plan_type = 'MEDICARE' AND (cpc.is_partbprimary = 'UNKNOWN' OR cpc.is_partbprimary IS NULL))
+               OR
+               (cpc.plan_type != 'MEDICARE' AND
+                (cpc.manual_determination_category = 'UNKNOWN' OR cpc.manual_determination_category IS NULL))
+           ))"
+            ))[0]->cnt;
+
+        }
+
         return view('app/dashboard', compact('keyNumbers', 'reimbursement', 'milliseconds',
             'businessNumbers',
             'incomingReports', 'tickets', 'supplyOrders',
             'numERx', 'numLabs', 'numImaging', 'numSupplyOrders',
             'newMCPAssociations', 'newNAAssociations',
-            'mcpClientMemos', 'naClientMemos'));
+            'mcpClientMemos', 'naClientMemos',
+            'proApptUpdates', 'naApptUpdates'));
     }
 
     public function dashboardMeasurementsTab(Request $request, $page = 1) {
@@ -557,15 +629,14 @@ WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$per
 SELECT count(measurement.id) as cnt
 FROM measurement
          join client on measurement.client_id = client.id
-         join care_month on client.id = care_month.client_id
 WHERE measurement.label NOT IN ('SBP', 'DBP')
   AND (measurement.is_cellular_zero = FALSE or measurement.is_cellular_zero IS NULL)
   AND measurement.is_removed IS FALSE
   AND measurement.ts IS NOT NULL
   AND measurement.client_bdt_measurement_id IS NOT NULL
   AND (measurement.status IS NULL OR (measurement.status <> 'ACK' AND measurement.status <> 'INVALID_ACK'))
-  AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
-  AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
+  AND EXTRACT(MONTH from measurement.created_at) = EXTRACT(MONTH from NOW())
+  AND EXTRACT(YEAR from measurement.created_at) = EXTRACT(YEAR from NOW())
 " .
                 (
                 $performer->pro->pro_type != 'ADMIN' ? $ifNotAdmin : ''
@@ -580,12 +651,20 @@ WHERE measurement.label NOT IN ('SBP', 'DBP')
                 "
 SELECT measurement.uid as uid,
        care_month.uid as care_month_uid,
+       care_month.start_date as care_month_start_date,
        measurement.label,
        measurement.value,
        measurement.sbp_mm_hg,
        measurement.dbp_mm_hg,
        measurement.numeric_value,
+       measurement.value_pulse,
+       measurement.value_irregular,
        measurement.ts,
+       client.id as client_id,
+       client.mcp_pro_id,
+       client.default_na_pro_id,
+       client.rmm_pro_id,
+       client.rme_pro_id,
        client.uid as client_uid,
        client.name_last,
        client.name_first,
@@ -596,11 +675,14 @@ FROM measurement
 WHERE measurement.label NOT IN ('SBP', 'DBP')
   AND (measurement.is_cellular_zero = FALSE or measurement.is_cellular_zero IS NULL)
   AND measurement.is_removed IS FALSE
+  AND measurement.has_been_stamped_by_mcp IS FALSE
   AND measurement.ts IS NOT NULL
   AND measurement.client_bdt_measurement_id IS NOT NULL
   AND (measurement.status IS NULL OR (measurement.status <> 'ACK' AND measurement.status <> 'INVALID_ACK'))
-  AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
-  AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
+  AND EXTRACT(MONTH from measurement.created_at) = EXTRACT(MONTH from NOW())
+  AND EXTRACT(YEAR from measurement.created_at) = EXTRACT(YEAR from NOW())
+  AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from NOW())
+  AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from NOW())
 " .
                 (
                 $performer->pro->pro_type != 'ADMIN' ? $ifNotAdmin : ''
@@ -686,6 +768,9 @@ WHERE measurement.label NOT IN ('SBP', 'DBP')
             $appointment->proUid = $appointment->pro->uid;
             $appointment->proName = $appointment->pro->displayName();
 
+            // insurance information
+            $appointment->coverage = $appointment->client->getPrimaryCoverageStatus();
+
             unset($appointment->client);
             unset($appointment->pro);
             unset($appointment->detail_json);
@@ -769,6 +854,7 @@ WHERE measurement.label NOT IN ('SBP', 'DBP')
 
         $pro = $this->pro;
         $term = $request->input('term') ? trim($request->input('term')) : '';
+        $originalTerm = $term;
         if (empty($term)) return '';
 
         // if multiple words in query, check for all (max 2)
@@ -779,27 +865,36 @@ WHERE measurement.label NOT IN ('SBP', 'DBP')
             $term2 = trim($terms[1]);
         }
 
+        $phoneNumberTerm = preg_replace("/[^0-9]/", "", $originalTerm );
+        if($phoneNumberTerm == ""){  //to avoid search with blank string
+            $phoneNumberTerm = $term;
+        }
+
         $clientQuery= Client::whereNull('shadow_pro_id')
-            ->where(function ($q) use ($term) {
+            ->where(function ($q) use ($term, $phoneNumberTerm) {
                 $q->where('name_first', 'ILIKE', '%' . $term . '%')
                     ->orWhere('name_last', 'ILIKE', '%' . $term . '%')
-                    ->orWhere('cell_number', 'ILIKE', '%' . $term . '%')
-                    ->orWhere('phone_home', 'ILIKE', '%' . $term . '%');
+                    ->orWhere('cell_number', 'ILIKE', '%' . $phoneNumberTerm . '%')
+                    ->orWhere('phone_home', 'ILIKE', '%' . $phoneNumberTerm . '%');
             });
 
         if(!empty($term2)) {
-            $clientQuery = $clientQuery->where(function ($q) use ($term2) {
+            $clientQuery = $clientQuery->where(function ($q) use ($term2, $phoneNumberTerm) {
                 $q->where('name_first', 'ILIKE', '%' . $term2 . '%')
                     ->orWhere('name_last', 'ILIKE', '%' . $term2 . '%')
-                    ->orWhere('cell_number', 'ILIKE', '%' . $term2 . '%')
-                    ->orWhere('phone_home', 'ILIKE', '%' . $term2 . '%');
+                    ->orWhere('cell_number', 'ILIKE', '%' . $phoneNumberTerm . '%')
+                    ->orWhere('phone_home', 'ILIKE', '%' . $phoneNumberTerm . '%');
             });
         }
 
         if(!($pro->pro_type === 'ADMIN' && $pro->can_see_any_client_via_search)) {
             $clientQuery->where(function ($q) use ($pro) {
-                $q->whereIn('id', $pro->getMyClientIds(true))
-                    ->orWhereNull('mcp_pro_id');
+                if($pro->pro_type === 'ADMIN') {
+                    $q->whereIn('id', $pro->getMyClientIds(true))->orWhereNull('mcp_pro_id');
+                }
+                else {
+                    $q->whereIn('id', $pro->getMyClientIds(true));
+                }
             });
         }
 
@@ -849,6 +944,25 @@ WHERE measurement.label NOT IN ('SBP', 'DBP')
                 ->orWhereRaw('LOWER(name_last::text) LIKE ?', ['%' . $term . '%'])
                 ->orWhereRaw('cell_number LIKE ?', ['%' . $term . '%']);
         });
+
+        $type = $request->input('type') ? trim($request->input('type')) : '';
+        if(!!$type) {
+            switch(strtolower($type)) {
+                case 'hcp':
+                    $pros->where('is_hcp', true);
+                    break;
+                case 'default-na': // TODO: fix condition for NA
+                    $pros->where('is_hcp', false)->where('pro_type', '!=', 'ADMIN');
+                    break;
+                case 'admin':
+                    $pros->where('pro_type', 'ADMIN');
+                    break;
+                case 'non-admin':
+                    $pros->where('pro_type', '!=', 'ADMIN');
+                    break;
+            }
+        }
+
         if($this->performer->pro && $this->performer->pro->pro_type != 'ADMIN'){
             $accessiblePros = ProProAccess::where('owner_pro_id', $this->performer->pro->id);
             $accessibleProIds = [];
@@ -856,6 +970,17 @@ WHERE measurement.label NOT IN ('SBP', 'DBP')
                 $accessibleProIds[] = $accessiblePro->id;
             }
             $accessibleProIds[] = $this->performer->pro->id;
+
+            // for dna, add pros accessible via pro teams
+            if($this->performer->pro->isDefaultNA()) {
+                $teams = $this->performer->pro->teamsWhereAssistant;
+                foreach ($teams as $team) {
+                    if(!in_array($team->mcp_pro_id, $accessibleProIds)) {
+                        $accessibleProIds[] = $team->mcp_pro_id;
+                    }
+                }
+            }
+
             $pros->whereIn('id', $accessibleProIds);
         }
         $suggestedPros = $pros->orderBy('name_last')->orderBy('name_first')->get();
@@ -878,6 +1003,13 @@ WHERE measurement.label NOT IN ('SBP', 'DBP')
         return view('app/pro-suggest', compact('suggestedPros'));
     }
 
+    public function canAccessPatient(Request $request, $uid) {
+        return json_encode([
+            "success" => true,
+            "data" => $this->performer->pro->canAccess($uid)
+        ]);
+    }
+
     public function proDisplayName(Request $request, Pro $pro) {
         return $pro ? $pro->displayName() : '';
     }
@@ -897,7 +1029,7 @@ WHERE measurement.label NOT IN ('SBP', 'DBP')
             });
         }
         $patients = $query->orderBy('name_last', 'asc')->orderBy('name_first', 'asc')->get();
-        $unmappedSMS = ClientSMS::where('client_id', null)->where('incoming_or_outgoing', 'INCOMING')->get();
+        $unmappedSMS = ClientSMS::where('client_id', null)->where('incoming_or_outgoing', 'INCOMING')->paginate(20);
         return view('app/unmapped-sms', compact('unmappedSMS', 'patients'));
     }
 
@@ -950,7 +1082,8 @@ WHERE measurement.label NOT IN ('SBP', 'DBP')
             return redirect()->to(route('dashboard'));
         }
 
-        $pros =  Pro::where('pro_type', '!=', 'ADMIN');
+        // dummy condition to get the chain-ability going
+        $pros =  Pro::where('id', '>', 0);
 
         if($request->input('q')) {
             $nameQuery = '%' . $request->input('q') . '%';

+ 76 - 0
app/Http/Controllers/NoteController.php

@@ -2,18 +2,23 @@
 
 namespace App\Http\Controllers;
 
+use App\Models\AppSession;
 use App\Models\Page;
+use App\Models\Point;
 use App\Models\Pro;
 use App\Models\SupplyOrder;
 use App\Models\Ticket;
 use Illuminate\Http\Request;
 use Illuminate\Support\Collection;
+use Illuminate\Support\Facades\Blade;
 use Illuminate\Support\Facades\Http;
 
 use App\Models\Note;
 use App\Models\Client;
 use App\Models\Section;
 use App\Models\SectionTemplate;
+use App\Models\Segment;
+use App\Models\SegmentTemplate;
 
 class NoteController extends Controller
 {
@@ -58,6 +63,7 @@ class NoteController extends Controller
         // other open supplyOrders as of today
         $otherOpenSupplyOrders = SupplyOrder::where('client_id', $patient->id)
             ->where('is_cancelled', false)
+            ->where('note_id', '<>', $note->id)
             ->get();
 
         return view('app.patient.note.dashboard', compact('patient', 'note',
@@ -66,6 +72,10 @@ class NoteController extends Controller
             'supplyOrdersOnNote', 'otherOpenSupplyOrders'));
     }
 
+    public function signConfirmation(Request $request, Client $patient, Note $note) {
+        return view('app.patient.note.sign-confirmation', compact('patient', 'note'));
+    }
+
     public function renderNote($noteUid, Request $request)
     {
 
@@ -80,6 +90,42 @@ class NoteController extends Controller
             compact('patient', 'note', 'section', 'page'));
     }
 
+    public function getHtmlForSegment($segmentUid, $sessionKey){
+
+        $performer = AppSession::where('session_key', $sessionKey)->first();
+        if(!$performer || !$performer->is_active){
+            return response()->json([
+                'success'=>false,
+                'message'=>'Invalid session key'
+            ]);
+        }
+        $pro = $performer->pro;
+
+        $segment = Segment::where('uid', $segmentUid)->first();
+        $segmentTemplate = $segment->segmentTemplate;
+
+        $note = $segment->note;
+        $patient = $note->client;
+
+        $data = compact('performer', 'pro', 'segment', 'segmentTemplate', 'note', 'patient');
+
+        //try {
+            $summaryHtml = view('app.patient.segment-templates.' . $segmentTemplate->internal_name . '/summary', $data)->render();
+            $editHtml = view('app.patient.segment-templates.' . $segmentTemplate->internal_name . '/edit', $data)->render();
+      //  } catch (\Throwable $e) {
+//            return response()->json([
+//                'success'=>false,
+//                'message'=>$e->getMessage()
+//            ]);
+       // }
+
+        return response()->json([
+            'success'=>true,
+            'summaryHtml' => $summaryHtml,
+            'editHtml' => $editHtml
+        ]);
+    }
+
     // JAVA ONLY
     // ... if hcpProId is passed, get from request
     public function getDefaultValueForSection($patientID, $sectionTemplateID)
@@ -236,6 +282,36 @@ class NoteController extends Controller
         ];
     }
 
+    // review log
+    public function reviewLog(Point $point) {
+        return view('app.patient.note.review-log', compact('point'));
+    }
+
+    // plan log
+    public function planLog(Point $point) {
+        return view('app.patient.note.plan-log', compact('point'));
+    }
+
+    // print/pdf
+    public function downloadAsPdf(Request $request, Note $note) {
+        $patient = $note->client;
+        if($request->input('html')) {
+            return view('app.patient.note.pdf', compact('note', 'patient'));
+        }
+        else {
+            $pdf = \PDF::loadView('app.patient.note.pdf', compact('note', 'patient'));
+            return $pdf->stream($note->created_at .'_' . 'note.pdf');
+        }
+    }
+
+    public function segmentSummary(Request $request, Segment $segment) {
+        return '<div class="mrv-content border-top px-3 pt-2 mt-3">' . @$segment->summary_html . '</div>';
+    }
+
+    public function medicationsCenter(Request $request, Client $patient, Note $note) {
+        return view('app.patient.medications-center', compact('patient', 'note'));
+    }
+
     // TODO move to utility
     private function callJava($request, $endPoint, $data, $guestAccessCode = null)
     {

+ 103 - 1
app/Http/Controllers/PatientController.php

@@ -8,6 +8,7 @@ use App\Models\CareMonth;
 use App\Models\Client;
 use App\Models\ClientBDTDevice;
 use App\Models\ClientInfoLine;
+use App\Models\Erx;
 use App\Models\Facility;
 use App\Models\Handout;
 use App\Models\IncomingReport;
@@ -26,6 +27,9 @@ use Illuminate\Http\Request;
 use Illuminate\Support\Facades\DB;
 use Illuminate\Support\Facades\File;
 
+use Illuminate\Support\Facades\Http;
+use PDF;
+
 class PatientController extends Controller
 {
 
@@ -369,7 +373,30 @@ class PatientController extends Controller
     }
 
     public function calendar(Request $request, Client $patient, Appointment $currentAppointment) {
-        return view('app.patient.appointment-calendar', compact('patient', 'currentAppointment'));
+        $pros = [];
+
+        if($this->pro && $this->pro->pro_type != 'ADMIN') {
+            $accessiblePros = ProProAccess::where('owner_pro_id', $this->pro->id)->get();
+            $accessibleProIds = [];
+            foreach($accessiblePros as $accessiblePro){
+                $accessibleProIds[] = $accessiblePro->id;
+            }
+            $accessibleProIds[] = $this->pro->id;
+
+            // for dna, add pros accessible via pro teams
+            if($this->performer->pro->isDefaultNA()) {
+                $teams = $this->performer->pro->teamsWhereAssistant;
+                foreach ($teams as $team) {
+                    if(!in_array($team->mcp_pro_id, $accessibleProIds)) {
+                        $accessibleProIds[] = $team->mcp_pro_id;
+                    }
+                }
+            }
+
+            $pros = Pro::whereIn('id', $accessibleProIds)->get();
+        }
+
+        return view('app.patient.appointment-calendar', compact('pros', 'patient', 'currentAppointment'));
     }
 
     public function programs(Request $request, Client $patient, $filter = '') {
@@ -382,6 +409,10 @@ class PatientController extends Controller
         return view('app.patient.flowsheets', compact('patient', 'pros', 'filter'));
     }
 
+    public function vitalsSettings(Request $request, Client $patient) {
+        return view('app.patient.vitals-settings', compact('patient'));
+    }
+
     public function vitalsGraph(Request $request, Client $patient, $filter = '') {
         $pros = $this->pros;
         return view('app.patient.vitals-graph', compact('patient', 'pros', 'filter'));
@@ -400,6 +431,65 @@ class PatientController extends Controller
         return view('app.patient.tickets', compact('patient', 'pros', 'allPros', 'type', 'currentTicket'));
     }
 
+    public function prescriptions(Request $request, Client $patient, String $type = '', String $currentErx = '') {
+        if(!!$currentErx) {
+            $currentErx = Erx::where('uid', $currentErx)->first();
+        }
+        return view('app.patient.prescriptions.index', compact('patient', 'type', 'currentErx'));
+    }
+
+    public function prescriptionsList(Request $request, Client $patient, String $type = '', String $currentErx = '') {
+        if(!!$currentErx) {
+            $currentErx = Erx::where('uid', $currentErx)->first();
+        }
+        $note = null;
+        if($request->input('noteUid')) {
+            $note = Note::where('uid', $request->input('noteUid'))->first();
+        }
+        return view('app.patient.prescriptions.list', compact('patient', 'type', 'currentErx', 'note'));
+    }
+
+    public function downloadPrescriptionAsPdf(Request $request, Erx $prescription){
+        if($request->input('html')) {
+            return view('app.patient.prescriptions.pdf.pdf-preview', compact('prescription'));
+        }
+        else {
+            $pdf = PDF::loadView('app.patient.prescriptions.pdf.pdf-preview', compact('prescription'));
+            return $pdf->download($prescription->created_at .'_' . 'erx.pdf');
+        }
+    }
+
+    public function transmitPrescription(Request $request, Erx $prescription){
+
+        // re-generate pdf with cover sheet as first page and save it to FS
+        $filePath = config('app.temp_dir') . "/{$prescription->uid}.pdf";
+        $pdf = PDF::loadView('app.patient.prescriptions.pdf.pdf-preview-with-cover-sheet', compact('prescription'));
+        $pdf->save($filePath);
+
+        // send it along with the rest of the params to /api/erx/transmit [multi-part POST]
+        $url =  config('stag.backendUrl') . '/erx/transmit';
+        $params = [
+            "uid" => $request->input('uid'),
+            "toWho" => $request->input('toWho'),
+            "toEmail" => $request->input('toEmail'),
+            "toFaxNumber" => $request->input('toFaxNumber'),
+            "toFaxNumberAttentionLine" => $request->input('toFaxNumberAttentionLine'),
+            "toFaxNumberCoverSheetMemo" => $request->input('toFaxNumberCoverSheetMemo'),
+        ];
+        if($request->input('copyToPatient')) {
+            $params["copyToPatientFaxNumber"] = $request->input('copyToPatientFaxNumber');
+            $params["copyToPatientEmail"] = $request->input('copyToPatientEmail');
+        }
+        $pdf = fopen($filePath, 'r');
+        $response = Http
+            ::attach('pdfSystemFile', $filePath, "{$prescription->uid}.pdf")
+            ->withHeaders(['sessionKey' => $request->cookie('sessionKey')])
+            ->post($url, $params)
+            ->json();
+        return $response;
+
+    }
+
     public function supplyOrders(Request $request, Client $patient, SupplyOrder $supplyOrder = null)
     {
         $products = Product::where('is_active', true)->orderBy('created_at', 'desc')->get();
@@ -436,6 +526,11 @@ class PatientController extends Controller
         return view('app.patient.insurance-coverage', compact('patient', 'mbPayers'));
     }
 
+    public function clientPrimaryCoverages(Request $request, Client $patient) {
+        $mbPayers = MBPayer::all();
+        return view('app.patient.client-primary-coverages', compact('patient', 'mbPayers'));
+    }
+
     public function mbClaim(Request $request, MBClaim $mbClaim) {
         return view('app.patient.mb-claim-single', compact('mbClaim'));
     }
@@ -443,4 +538,11 @@ class PatientController extends Controller
     public function accounts(Request $request, Client $patient) {
         return view('app.patient.accounts', compact('patient'));
     }
+
+    public function careMonthMatrix(Request $request, CareMonth $careMonth) {
+        return view('app.patient.care-month.matrix', [
+            'patient' => $careMonth->patient,
+            'careMonth' => $careMonth,
+        ]);
+    }
 }

+ 238 - 10
app/Http/Controllers/PracticeManagementController.php

@@ -25,10 +25,12 @@ use App\Models\ProProAccess;
 use App\Models\ProRate;
 use App\Models\ProSpecificAvailability;
 use App\Models\ProSpecificUnavailability;
+use App\Models\ProTeam;
 use App\Models\ProTextShortcut;
 use App\Models\ProTransaction;
 use App\Models\Shipment;
 use App\Models\SupplyOrder;
+use App\Models\Team;
 use App\Models\Ticket;
 use App\Models\ClientMeasurementDaysPerMonth;
 use Illuminate\Support\Facades\DB;
@@ -180,6 +182,17 @@ class PracticeManagementController extends Controller
         return view('app.practice-management.notes', compact('notes', 'filter'));
     }
 
+    public function dnaNotesPendingMcpSign(Request $request)
+    {
+        $proID = $this->performer()->pro->id;
+        $notes = Note::where('ally_pro_id', $proID)
+            ->where('is_signed_by_hcp', false)
+            ->where('is_cancelled', false)
+            ->orderBy('created_at', 'desc')
+            ->get();
+        return view('app.practice-management.dna-notes-pending-mcp-sign', compact('notes'));
+    }
+
     public function naBillableSignedNotes(Request $request)
     {
 
@@ -359,6 +372,45 @@ class PracticeManagementController extends Controller
         return view('app.practice-management.my-favorites', compact('myFavorites', 'filter'));
     }
 
+    public function patientsWithoutCoverage(Request $request, $filter = 'all')
+    {
+        $performer = $this->performer();
+
+        $sql = "SELECT cl.uid, cl.name_first, cl.name_last FROM client cl ";
+
+        $joinClause = 'LEFT JOIN client_primary_coverage cpc ON cl.latest_client_primary_coverage_id = cpc.id ';
+        $withoutCondition = "cl.latest_client_primary_coverage_id IS NULL";
+        $pendingCondition = "
+(cl.latest_client_primary_coverage_id IS NOT NULL -- coverage exists, but status is null or unknown
+    AND (
+               (cpc.plan_type = 'MEDICARE' AND (cpc.is_partbprimary = 'UNKNOWN' OR cpc.is_partbprimary IS NULL))
+               OR
+               (cpc.plan_type != 'MEDICARE' AND
+                (cpc.manual_determination_category = 'UNKNOWN' OR cpc.manual_determination_category IS NULL))
+           ))";
+
+        switch ($filter) {
+            case 'without-coverage-information':
+                $sql .= 'WHERE cl.shadow_pro_id IS NULL AND ';
+                $sql .= $withoutCondition;
+                break;
+            case 'pending-coverage-verification':
+                $sql .= $joinClause . 'WHERE cl.shadow_pro_id IS NULL AND ';
+                $sql .= $pendingCondition;
+                break;
+            default:
+                $sql .= $joinClause . 'WHERE cl.shadow_pro_id IS NULL AND ';
+                $sql .= '(' . $withoutCondition . ' OR ' . $pendingCondition . ')';
+                break;
+        }
+
+        $sql .= ' ORDER BY cl.name_first ASC';
+
+        $pendingCoverage = DB::select(DB::raw($sql));
+
+        return view('app.practice-management.patients-without-coverage', compact('pendingCoverage', 'filter'));
+    }
+
     public function proAvailability(Request $request, $proUid = null)
     {
         $performer = $this->performer();
@@ -797,7 +849,7 @@ class PracticeManagementController extends Controller
                 true);
         }
 
-        $notes = $notes->orderBy('effective_dateest', 'desc')->paginate(10);
+        $notes = $notes->orderBy('effective_dateest', 'desc')->paginate(20);
 
         return view('app.practice-management.billing-manager', compact('notes', 'allPros', 'expectedForHcp', 'targetPro', 'proUid', 'filters'));
     }
@@ -958,7 +1010,7 @@ ORDER BY ts DESC
         //Only medicare claims
         $claims = [];
         foreach ($allClaims as $claim) {
-            if ($claim->client != null && $claim->client->is_part_b_primary == 'YES' && !$claim->edi) {
+            if ($claim->client != null && $claim->client->getPrimaryCoverageStatus() == 'YES' && !$claim->edi) {
                 $claims[] = $claim;
             }
         }
@@ -1376,7 +1428,7 @@ FROM claim
     left join app_session on claim.status_updated_by_session_id = app_session.id
     left join pro sp on app_session.pro_id = sp.id
 --WHERE claim.status IS NULL OR claim.status = 'NEW'
-WHERE (claim.status is NULL OR claim.status NOT IN ('CANCELLED', 'ABANDONED'))
+WHERE (claim.status is NULL OR claim.status NOT IN ('CANCELLED', 'ABANDONED'" . ($request->input('show-submitted') ? "" : ", 'SUBMITTED'") . "))
 -- AND claim.current_version_id IS NOT NULL
 AND (client.name_first ILIKE :q OR
      client.name_last ILIKE :q OR
@@ -1385,7 +1437,7 @@ AND (client.name_first ILIKE :q OR
 AND (claim.created_at >= :from AND claim.created_at <= :to)
 " . ($hcpPro ? "AND claim.pro_id = :hcp" : '') . "
 AND claim.id IN (SELECT mb_claim.claim_id FROM mb_claim)
-ORDER BY claim.created_at ASC
+ORDER BY claim.created_at DESC
 --OFFSET 0 LIMIT 15
 "), $params);
 
@@ -1408,7 +1460,8 @@ ORDER BY claim.created_at ASC
             ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
             ->where('rm_total_time_in_seconds', '>=', 4200) // at 4200 (70 minutes, it becomes eligible for plus40)
             ->where('number_of_days_with_remote_measurements', '>=', 16 )
-            ->whereRaw('has_anyone_interacted_with_client_about_rm_outside_note IS  TRUE OR has_mcp_rm_interacted_by_note IS  TRUE ')
+            ->whereRaw('is_rm_time_waived IS NOT TRUE')
+            ->whereRaw('(has_anyone_interacted_with_client_about_rm_outside_note IS  TRUE OR has_mcp_rm_interacted_by_note IS  TRUE )')
             ->count();
 
         $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP_PLUS_40_ifHadInteraction'] = CareMonth::where('is_bill_closed', false)
@@ -1419,7 +1472,8 @@ ORDER BY claim.created_at ASC
             ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
             ->where('rm_total_time_in_seconds', '>=', 4200) // at 4200 (70 minutes, it becomes eligible for plus40)
             ->where('number_of_days_with_remote_measurements', '>=', 16 )
-            ->whereRaw('has_anyone_interacted_with_client_about_rm_outside_note IS NOT TRUE AND has_mcp_rm_interacted_by_note IS NOT TRUE AND is_rm_interaction_waived IS NOT TRUE ')
+            ->whereRaw('is_rm_time_waived IS NOT TRUE')
+            ->whereRaw('(has_anyone_interacted_with_client_about_rm_outside_note IS NOT TRUE AND has_mcp_rm_interacted_by_note IS NOT TRUE AND is_rm_interaction_waived IS NOT TRUE )')
             ->count();
 
         $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP_PLUS_20'] = CareMonth::where('is_bill_closed', false)
@@ -1431,7 +1485,8 @@ ORDER BY claim.created_at ASC
             ->where('rm_total_time_in_seconds', '<', 4200)
             ->where('rm_total_time_in_seconds', '>=', 3000) // at 3000 (50 minutes, it becomes eligible for plus20)
             ->where('number_of_days_with_remote_measurements', '>=', 16 )
-            ->whereRaw('has_anyone_interacted_with_client_about_rm_outside_note IS TRUE OR has_mcp_rm_interacted_by_note IS TRUE')
+            ->whereRaw('is_rm_time_waived IS NOT TRUE')
+            ->whereRaw('(has_anyone_interacted_with_client_about_rm_outside_note IS TRUE OR has_mcp_rm_interacted_by_note IS TRUE)')
             ->count();
 
         $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP_PLUS_20_ifHadInteraction'] = CareMonth::where('is_bill_closed', false)
@@ -1443,7 +1498,8 @@ ORDER BY claim.created_at ASC
             ->where('rm_total_time_in_seconds', '<', 4200)
             ->where('rm_total_time_in_seconds', '>=', 3000) // at 3000 (50 minutes, it becomes eligible for plus20)
             ->where('number_of_days_with_remote_measurements', '>=', 16 )
-            ->whereRaw('has_anyone_interacted_with_client_about_rm_outside_note IS NOT TRUE AND has_mcp_rm_interacted_by_note IS NOT TRUE AND is_rm_interaction_waived IS NOT TRUE ')
+            ->whereRaw('is_rm_time_waived IS NOT TRUE')
+            ->whereRaw('(has_anyone_interacted_with_client_about_rm_outside_note IS NOT TRUE AND has_mcp_rm_interacted_by_note IS NOT TRUE AND is_rm_interaction_waived IS NOT TRUE )')
             ->count();
 
         $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP'] = CareMonth::where('is_bill_closed', false)
@@ -1452,12 +1508,29 @@ ORDER BY claim.created_at ASC
             ->whereNotNull('company_location_id')
             ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
             ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
-            ->where('rm_total_time_in_seconds', '<', 3000)
+            ->whereRaw('is_rm_time_waived IS NOT TRUE')
+            ->whereRaw('(rm_total_time_in_seconds < 3000 OR (rm_total_time_in_seconds >= 3000 AND is_rm_interaction_waived IS TRUE))')
+            ->where('number_of_days_with_remote_measurements', '>=', 16 )
+            ->count();
+
+        $keyNumbers['careMonthsEligibleForBillGeneration_RMB'] = CareMonth::where('is_bill_closed', false)
+            ->whereNotNull('company_pro_id')
+            ->whereNotNull('company_pro_payer_id')
+            ->whereNotNull('company_location_id')
+            ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
+            ->whereRaw('is_rm_time_waived IS TRUE')
             ->where('number_of_days_with_remote_measurements', '>=', 16 )
             ->count();
 
+        $keyNumbers['careMonthsWith16OrMoreMeasurementDays'] = CareMonth::where('is_bill_closed', false)
+            ->where('number_of_days_with_remote_measurements', '>=', 16 )
+            ->count();
+
+        $careMonthsWith16PlusMeasurements = CareMonth::where('is_bill_closed', false)
+            ->where('number_of_days_with_remote_measurements', '>=', 16 )->get();
+
 
-        return  view('app.practice-management.rm-launch-and-clean', compact('keyNumbers'));
+        return  view('app.practice-management.rm-launch-and-clean', compact('keyNumbers', 'careMonthsWith16PlusMeasurements'));
     }
 
     public function processNotes(Request  $request) {
@@ -1572,6 +1645,66 @@ ORDER BY claim.created_at ASC
         return  view('app.practice-management.process-notes', compact('mode', 'counts'));
     }
 
+    public function notesProcessingCenter(Request  $request) {
+
+        $notes = Note::where('is_cancelled', false);
+
+        // filters
+        $proUid = $request->input('proUid');
+        if($proUid) {
+            $fPro = Pro::where('uid', $proUid)->first();
+            if($fPro) {
+                $notes = $notes->where('hcp_pro_id', $fPro->id);
+            }
+        }
+        $proSigned = $request->input('proSigned');
+        switch($proSigned) {
+            case 'yes': $notes = $notes->where('is_signed_by_hcp', true); break;
+            case 'no': $notes = $notes->where('is_signed_by_hcp', '!=', true); break;
+        }
+        $billingMarkedDone = $request->input('billingMarkedDone');
+        switch($billingMarkedDone) {
+            case 'yes': $notes = $notes->where('is_billing_marked_done', true); break;
+            case 'no': $notes = $notes->where('is_billing_marked_done', '!=', true); break;
+        }
+        $billingClosed = $request->input('billingClosed');
+        switch($billingClosed) {
+            case 'yes': $notes = $notes->where('is_bill_closed', true); break;
+            case 'no': $notes = $notes->where('is_bill_closed', '!=', true); break;
+        }
+        $claimingClosed = $request->input('claimingClosed');
+        switch($claimingClosed) {
+            case 'yes': $notes = $notes->where('is_claim_closed', true); break;
+            case 'no': $notes = $notes->where('is_claim_closed', '!=', true); break;
+        }
+        $allClaimsSubmitted = $request->input('allClaimsSubmitted');
+        if($allClaimsSubmitted) {
+            // TODO
+        }
+        $goodBad = $request->input('goodBad');
+        switch($goodBad) {
+            case 'good': $notes = $notes->whereRaw("(detail_json)::json->>'isBad' = 'false'"); break;
+            case 'bad': $notes = $notes->whereRaw("(detail_json)::json->>'isBad' = 'true'"); break;
+            case 'unclassified': $notes = $notes->whereRaw("(detail_json)::json->>'isBad' is null"); break;
+        }
+        $startDate = $request->input('startDate');
+        if($startDate) {
+            $notes = $notes->where('effective_dateest', '>=', $startDate);
+        }
+        $endDate = $request->input('endDate');
+        if($endDate) {
+            $notes = $notes->where('effective_dateest', '<=', $endDate);
+        }
+        $mcPartB = $request->input('mcPartB');
+        if($mcPartB) {
+            // TODO
+        }
+
+        $notes = $notes->orderBy('effective_dateest')->paginate(10);
+
+        return  view('app.practice-management.notes-processing-center', compact('notes'));
+    }
+
     public function getNextNote(Request $request, $mode)
     {
         $note = null;
@@ -1764,4 +1897,99 @@ ORDER BY claim.created_at ASC
         return view('app.practice-management.generic-bills');
     }
 
+    public function billsUnderProcessing(Request $request)
+    {
+
+        $bills = Bill::where('is_cancelled', false)
+            ->where(function ($query) {   // mcp of any client program and program OB pending
+                $query
+                    ->where(function ($_query) {
+                        $_query->where('hcp_pro_id', $this->pro->id)
+                            ->where('hcp_expected_payment_amount', '>', 0)
+                            ->where('has_hcp_been_paid', false)
+                            ->where('is_signed_by_hcp', true);
+                    })
+                    ->orWhere(function ($_query) {
+                        $_query->where('cm_pro_id', $this->pro->id)
+                            ->where('cm_expected_payment_amount', '>', 0)
+                            ->where('has_cm_been_paid', false)
+                            ->where('is_signed_by_cm', true);
+                    })
+                    ->orWhere(function ($_query) {
+                        $_query->where('rme_pro_id', $this->pro->id)
+                            ->where('rme_expected_payment_amount', '>', 0)
+                            ->where('has_rme_been_paid', false)
+                            ->where('is_signed_by_rme', true);
+                    })
+                    ->orWhere(function ($_query) {
+                        $_query->where('rmm_pro_id', $this->pro->id)
+                            ->where('rmm_expected_payment_amount', '>', 0)
+                            ->where('has_rmm_been_paid', false)
+                            ->where('is_signed_by_rmm', true);
+                    })
+                    ->orWhere(function ($_query) {
+                        $_query->where('generic_pro_id', $this->pro->id)
+                            ->where('generic_pro_expected_payment_amount', '>', 0)
+                            ->where('has_generic_pro_been_paid', false)
+                            ->where('is_signed_by_generic_pro', true);
+                    });
+            })
+            ->orderBy('created_at', 'DESC')
+            ->paginate();
+
+        return view('app.practice-management.bills-under-processing', compact('bills'));
+
+    }
+
+    public function careMonthReport(Request $request) {
+        $m = $request->input('m');
+        $y = $request->input('y');
+        if(!$m || !$y) {
+            $date = date('Y-m-01');
+        }
+        else {
+            $date = date('Y-m-d', strtotime("$m/1/$y"));
+        }
+
+        $pro = $this->pro;
+
+        $records = DB::select("
+SELECT cm.id                                as care_month_id,
+       cm.uid                               as care_month_uid,
+       c.id                                 as client_id,
+       c.uid                                as client_uid,
+       cm.number_of_days_with_remote_measurements,
+       cm.rm_total_time_in_seconds_by_mcp,
+       cm.rm_total_time_in_seconds_by_rme_pro,
+       cm.rm_total_time_in_seconds_by_rmm_pro,
+       cm.mcp_pro_id,
+       cm.rme_pro_id,
+       cm.rmm_pro_id,
+       (c.name_first || ' ' || c.name_last) as client_name
+FROM care_month cm
+         JOIN client c on cm.client_id = c.id
+WHERE cm.start_date = :startDate
+  AND (cm.mcp_pro_id = :proID OR
+       cm.rme_pro_id = :proID OR
+       cm.rmm_pro_id = :proID)
+ORDER BY c.name_last, c.name_first
+            ",
+            ['startDate' => $date, 'proID' => $pro->id]
+        );
+
+        return view('app.practice-management.care-month-report', compact('records', 'date'));
+    }
+
+    public function myTeams(Request $request) {
+        $pro = $this->pro;
+
+        // get all teams where the authed-pro is the assistant pro
+        $teams = ProTeam::where('assistant_pro_id', $pro->id)
+            ->where('is_active', true)
+            ->orderBy('slug')
+            ->get();
+
+        return view('app.practice-management.my-teams', compact('teams'));
+    }
+
 }

+ 17 - 0
app/Http/Middleware/ProAuthenticated.php

@@ -4,6 +4,7 @@ namespace App\Http\Middleware;
 
 use App\Models\AppSession;
 use Closure;
+use Illuminate\Support\Facades\Http;
 
 class ProAuthenticated
 {
@@ -29,6 +30,22 @@ class ProAuthenticated
             return redirect($authUrl);
         }
 
+        //log session activity 
+        $this->logSessionActivity($sessionKey);
+
         return $next($request);
     }
+
+    private function logSessionActivity($sessionKey)
+    {
+        
+        $url =  config('stag.backendUrl') . '/session/ping';
+        $response = Http::asForm()
+            ->withHeaders([
+                'sessionKey' => $sessionKey
+            ])
+            ->post($url,[])
+            ->body();
+        return $response;
+    }
 }

+ 4 - 0
app/Models/AppointmentConfirmationDecision.php

@@ -10,4 +10,8 @@ class AppointmentConfirmationDecision extends Model
 {
     protected $table = 'appointment_confirmation_decision';
 
+    public function session() {
+        return $this->hasOne(AppSession::class, 'id', 'created_by_session_id');
+    }
+
 }

+ 6 - 0
app/Models/CareMonth.php

@@ -97,4 +97,10 @@ class CareMonth extends Model
             ->orderBy('position_index', 'ASC')
             ->orderBy('code', 'ASC');
     }
+
+    public function rmSetupClaim()
+    {
+        return $this->hasOne(Claim::class, 'id', 'rm_setup_claim_id')
+            ->where('status', '<>', 'CANCELLED');
+    }
 }

+ 149 - 3
app/Models/Client.php

@@ -13,6 +13,28 @@ class Client extends Model
 {
     protected $table = 'client';
 
+    public function primaryCoverages()
+    {
+        return $this->hasMany(ClientPrimaryCoverage::class, 'client_id', 'id')
+            ->orderBy('created_at', 'desc');
+    }
+
+    public function latestClientPrimaryCoverage(){
+        return $this->hasOne(ClientPrimaryCoverage::class, 'id', 'latest_client_primary_coverage_id');
+    }
+	public function latestNewClientPrimaryCoverage(){
+        return $this->hasOne(ClientPrimaryCoverage::class, 'id', 'latest_new_client_primary_coverage_id');
+    }
+	public function latestAutoRefreshClientPrimaryCoverage(){
+        return $this->hasOne(ClientPrimaryCoverage::class, 'id', 'latest_auto_refresh_client_primary_coverage_id');
+    }
+	public function latestManualClientPrimaryCoverage(){
+        return $this->hasOne(ClientPrimaryCoverage::class, 'id', 'latest_manual_client_primary_coverage_id');
+    }
+	public function temporaryOutsiderNewClientPrimaryCoverage(){
+        return $this->hasOne(ClientPrimaryCoverage::class, 'id', 'temporary_outsider_new_client_primary_coverage_id');
+    }
+
     public function displayName()
     {
         return $this->name_last . ', ' . $this->name_first;
@@ -69,6 +91,13 @@ class Client extends Model
             ->orderBy('effective_dateest', 'desc');
     }
 
+    public function prescriptions()
+    {
+        return $this->hasMany(Erx::class, 'client_id', 'id')
+            ->orderByRaw('note_id DESC NULLS LAST')
+            ->orderBy('created_at', 'desc');
+    }
+
     public function notesAscending()
     {
         return $this->hasMany(Note::class, 'client_id', 'id')
@@ -279,9 +308,19 @@ class Client extends Model
     public function upcomingAppointments()
     {
         return $this->hasMany(Appointment::class, 'client_id', 'id')
-            // ->where('raw_start_time', '>', date('Y-m-d H:i:s'))
+            ->where('raw_date', '>=', date('Y-m-d'))
             ->whereIn('status', ['CREATED', 'CONFIRMED'])
-            ->orderBy('start_time', 'desc');
+            ->orderBy('start_time', 'desc')
+            ->limit(5);
+    }
+
+    public function nextAppointment() {
+        return Appointment
+            ::where('client_id', $this->id)
+            ->where('raw_date', '>=', DB::raw('NOW()'))
+            ->whereIn('status', ['CONFIRMED', 'CREATED'])
+            ->orderBy('start_time')
+            ->first();
     }
 
     public function appointmentsFromLastWeek()
@@ -441,7 +480,7 @@ class Client extends Model
         $pro = $this->rme;
         if ($pro && $pro->id) $pros[] = ["pro" => $pro->displayName(), "association" => 'RME'];
         $pro = $this->defaultNaPro;
-        if ($pro && $pro->id) $pros[] = ["pro" => $pro->displayName(), "association" => 'Default NA'];
+        if ($pro && $pro->id) $pros[] = ["pro" => $pro->displayName(), "association" => 'Nurse'];
 
         // via client pro access
         $cpAccesses = ClientProAccess::where('client_id', $this->id)->where('is_active', true)->get();
@@ -616,6 +655,11 @@ class Client extends Model
             ->orderBy('code', 'ASC');
     }
 
+    public function cmSetupNote()
+    {
+        return $this->hasOne(Note::class, 'id', 'cm_setup_note_id');
+    }
+
     public function defaultMcpCompanyPro()
     {
         return $this->hasOne(CompanyPro::class, 'id', 'default_mcp_company_pro_id');
@@ -631,4 +675,106 @@ class Client extends Model
         return $this->hasOne(CompanyLocation::class, 'id', 'default_mcp_company_location_id');
     }
 
+    public function hasNewNoteForPro($_pro) {
+        $count = Note::where('client_id', $this->id)->where('hcp_pro_id', $_pro->id)->where('is_cancelled', false)->where('new_or_fu_or_na', 'NEW')->count();
+        return !!$count;
+    }
+
+    public function systemSourcePro()
+    {
+        return $this->hasOne(Pro::class, 'id', 'system_source_pro_id');
+    }
+
+    public function systemSourceProTeam()
+    {
+        return $this->hasOne(ProTeam::class, 'id', 'system_source_pro_team_id');
+    }
+
+    public function recentNotes($_pro = null) {
+        $notes = Note::where('client_id', $this->id)->where('is_cancelled', false);
+        if($_pro) {
+            $notes = $notes->where('hcp_pro_id', $_pro->id);
+        }
+        $notes = $notes->orderBy('effective_dateest', 'DESC')->limit(5)->get();
+        return $notes;
+    }
+
+    public function cmMeasurementsMatrix($_careMonth = null) {
+
+        $days = [];
+
+        $matches = DB::select(
+            "
+SELECT m.id   AS measurement_id,
+       m.uid  AS measurement_uid,
+       cm.id  AS care_month_id,
+       cm.uid AS care_month_uid,
+       m.label,
+       m.value,
+       m.dbp_mm_hg,
+       m.sbp_mm_hg,
+       m.value_pulse,
+       m.value_irregular,
+       m.numeric_value,
+       m.effective_date,
+       m.ts,
+       m.has_been_stamped_by_mcp,
+       m.has_been_stamped_by_non_hcp
+FROM measurement m
+         JOIN care_month cm ON m.care_month_id = cm.id
+WHERE m.care_month_id = :careMonthID
+        AND m.label NOT IN ('SBP', 'DBP')
+        AND m.bdt_measurement_id IS NOT NULL
+        AND m.is_removed IS FALSE
+        AND (m.is_cellular_zero = FALSE or m.is_cellular_zero IS NULL)
+        AND m.ts IS NOT NULL
+        AND m.client_bdt_measurement_id IS NOT NULL
+ORDER BY m.ts DESC
+            ",
+            ['careMonthID' => $_careMonth->id]
+        );
+
+        foreach ($matches as $match) {
+            $time = (floor($match->ts / 1000));
+            $realTimezone = resolve_timezone('EASTERN');
+            $date = new \DateTime("@$time");
+            $date->setTimezone(new \DateTimeZone($realTimezone));
+            $match->date = $date->format("m/d/Y");
+            $match->dateYMD = $date->format("Y-m-d");
+            $match->time = $date->format("h:i A");
+
+            // get existing entries for listing
+            $match->entries = CareMonthEntry::where('care_month_id', $match->care_month_id)
+                ->where('is_removed', false)
+                ->where('effective_date', $match->dateYMD)
+                ->orderBy('created_at')
+                ->get();
+
+            if(!isset($days[$match->date])) {
+                $days[$match->date] = [];
+            }
+            $days[$match->date][] = $match;
+        }
+
+        return $days;
+
+    }
+
+    public function getPrimaryCoverage()
+    {
+        // try the latest manual coverage
+        $coverage = $this->latestManualClientPrimaryCoverage;
+        if (!$coverage) {
+            // try the latest coverage
+            $coverage = $this->latestClientPrimaryCoverage;
+        }
+        return $coverage;
+    }
+
+    // return value will be YES, NO or UNKNOWN
+    public function getPrimaryCoverageStatus() {
+        $coverage = $this->getPrimaryCoverage();
+        if(!$coverage) return 'NO';
+        return $coverage->getStatus();
+    }
 }

+ 58 - 0
app/Models/ClientPrimaryCoverage.php

@@ -0,0 +1,58 @@
+<?php
+
+namespace App\Models;
+
+use Illuminate\Database\Eloquent\Factories\HasFactory;
+use Illuminate\Database\Eloquent\Model;
+
+class ClientPrimaryCoverage extends Model
+{    
+    protected $table = 'client_primary_coverage';
+
+    public function getStatus() {
+        $status = 'NO';
+
+        // if medicare, check is_partbprimary
+        if($this->plan_type === 'MEDICARE') {
+            $status = $this->is_partbprimary;
+        }
+        else {
+            if(!$this->is_manually_determined) {
+                // AUTO determination of non-medicare not yet supported
+                $status = 'NO';
+            }
+            else {
+                switch($this->manual_determination_category) {
+                    case 'COVERED':
+                        $status = 'YES';
+                        break;
+                    case 'NOT_COVERED':
+                    case 'INVALID':
+                        $status = 'NO';
+                        break;
+                    default:
+                        $status = $this->manual_determination_category;
+                        break;
+                }
+            }
+        }
+
+        return $status;
+    }
+
+    public function toString() {
+        $parts = [];
+        $parts[] = $this->plan_type;
+        if($this->plan_type === 'MEDICARE') {
+            if($this->is_partbprimary === 'YES') {
+                $parts[] = 'Part B';
+            }
+        }
+        else {
+            if(@$this->plan_name) $parts[] = ' / ' . $this->plan_name;
+            if(@$this->plan_identifier) $parts[] = ' / ' . $this->plan_identifier;
+        }
+        return implode(" ", $parts);
+    }
+
+}

+ 31 - 0
app/Models/Erx.php

@@ -0,0 +1,31 @@
+<?php
+
+namespace App\Models;
+
+# use Illuminate\Database\Eloquent\Model;
+
+class Erx extends Model
+{
+    protected $table = "erx";
+
+    public function managerPro(){
+        return $this->hasOne(Pro::class, 'id', 'manager_pro_id');
+    }
+
+    public function hcpPro(){
+        return $this->hasOne(Pro::class, 'id', 'hcp_pro_id');
+    }
+
+    public function patient(){
+        return $this->hasOne(Client::class, 'id', 'client_id');
+    }
+
+    public function client(){
+        return $this->hasOne(Client::class, 'id', 'client_id');
+    }
+
+    public function note(){
+        return $this->hasOne(Note::class, 'id', 'note_id');
+    }
+
+}

+ 29 - 0
app/Models/Note.php

@@ -38,6 +38,12 @@ class Note extends Model
         return $this->hasOne(Pro::class, 'id', 'ally_pro_id');
     }
 
+    public function cmSetupClaim()
+    {
+        return $this->hasOne(Claim::class, 'id', 'cm_setup_claim_id')
+            ->where('status', '<>', 'CANCELLED');
+    }
+
     public function bills()
     {
         return $this->hasMany(Bill::class, 'note_id', 'id')
@@ -57,6 +63,14 @@ class Note extends Model
             ->orderBy('position_index', 'asc');
     }
 
+    public function segments()
+    {
+        return $this->hasMany(Segment::class, 'note_id', 'id')
+            ->where('id', '!=', $this->core_segment_id) // dont include core-segment
+            ->where('is_active', true)
+            ->orderBy('position_index', 'asc');
+    }
+
     public function reasons()
     {
         return $this->hasMany(NoteReason::class, 'note_id', 'id');
@@ -98,4 +112,19 @@ class Note extends Model
         return $this->hasOne(NotePickupForProcessing::class, 'id', 'current_note_pickup_for_processing_id');
     }
 
+    public function visitTemplate()
+    {
+        return $this->hasOne(VisitTemplate::class, 'id', 'visit_template_id');
+    }
+
+    public function hasTreatmentServicesBillByHCP()
+    {
+        $bills = Bill::where('note_id', $this->id)
+            ->where('bill_service_type', '<>', 'GENERIC')
+            ->where('code', 'Treatment Services')
+            ->where('is_cancelled', false)
+            ->count();
+        return !!$bills;
+    }
+
 }

+ 5 - 0
app/Models/NotePickupForProcessing.php

@@ -13,4 +13,9 @@ class NotePickupForProcessing extends Model
         return $this->hasOne(Pro::class, 'id', 'pro_id');
     }
 
+    public function note()
+    {
+        return $this->hasOne(Note::class, 'id', 'note_id');
+    }
+
 }

+ 11 - 0
app/Models/NotePoint.php

@@ -0,0 +1,11 @@
+<?php
+
+namespace App\Models;
+
+# use Illuminate\Database\Eloquent\Model;
+
+class NotePoint extends Model
+{
+    protected $table = 'note_point';
+
+}

+ 169 - 0
app/Models/Point.php

@@ -0,0 +1,169 @@
+<?php
+
+namespace App\Models;
+
+# use Illuminate\Database\Eloquent\Model;
+
+class Point extends Model
+{
+    protected $table = 'point';
+
+    public function childReviews()
+    {
+        return $this->hasMany(Point::class, 'parent_point_id', 'id')
+            ->where('category', 'REVIEW')
+            ->orderBy('created_at', 'DESC');
+    }
+
+    public function childReviewAddedInNote($_note)
+    {
+        $review = Point::where('added_in_note_id', $_note->id)
+            ->where('category', 'REVIEW')
+            ->where('parent_point_id', $this->id)
+            ->orderBy('created_at', 'DESC')
+            ->first();
+        if(!!$review) {
+            $review->data = json_decode($review->data);
+        }
+        return $review;
+    }
+
+    public function childPlanAddedInNote($_note)
+    {
+        $review = Point::where('added_in_note_id', $_note->id)
+            ->where('category', 'PLAN')
+            ->where('parent_point_id', $this->id)
+            ->orderBy('created_at', 'DESC')
+            ->first();
+        if(!!$review) {
+            $review->data = json_decode($review->data);
+        }
+        return $review;
+    }
+
+    public function lastChildReview()
+    {
+        return $this->hasOne(Point::class, 'id', 'last_child_review_point_id');
+    }
+
+    public function lastChildReviewNote()
+    {
+        return $this->hasOne(Note::class, 'id', 'last_child_review_point_scoped_note_id');
+    }
+
+    public function childPlans()
+    {
+        return $this->hasMany(Point::class, 'parent_point_id', 'id')
+            ->where('category', 'PLAN')
+            ->orderBy('created_at', 'DESC');
+    }
+
+    public function lastChildPlan()
+    {
+        return $this->hasOne(Point::class, 'id', 'last_child_plan_point_id');
+    }
+
+    public function lastChildPlanNote()
+    {
+        return $this->hasOne(Note::class, 'id', 'last_child_plan_point_scoped_note_id');
+    }
+
+    public function client()
+    {
+        return $this->hasOne(Client::class, 'id', 'client_id');
+    }
+
+    public function note()
+    {
+        return $this->hasOne(Note::class, 'id', 'added_in_note_id');
+    }
+
+    public function relevanceToNote($_note) {
+        return NotePoint
+            ::where('is_active', true)
+            ->where('note_id', $_note->id)
+            ->where('point_id', $this->id)
+            ->first();
+    }
+
+    public static function getGlobalSingletonOfCategory(Client $_patient, String $_category, $_assoc = false) {
+        $point = Point
+            ::where('client_id', $_patient->id)
+            ->where('category', $_category)
+            ->orderBy('created_at', 'DESC')
+            ->first();
+        if ($point && @$point->data) {
+            $point->data = json_decode($point->data, $_assoc);
+        }
+        return $point;
+    }
+
+    public static function getIntakePointsOfCategory(Client $_patient, String $_category, Note $_note, $_assoc = false) {
+        $points = Point
+            ::where('client_id', $_patient->id)
+            ->where('category', $_category)
+            ->where('is_removed_due_to_entry_error', false)
+            ->where(function ($query1) use ($_note) {
+                $query1
+                    ->where('addition_reason_category', 'ON_INTAKE')
+                    ->orWhere(function ($query2) use ($_note) {
+                        $query2->where('addition_reason_category', 'DURING_VISIT')
+                            ->where('added_in_note_id', '<>', $_note->id);
+                    });
+            })
+            ->where(function ($query1) use ($_note) {
+                $query1
+                    ->where('is_removed', false)
+                    ->orWhere(function ($query2) use ($_note) {
+                        $query2->where('is_removed', true)
+                            ->where('removed_in_note_id', $_note->id);
+                    });
+            })
+            ->orderBy('created_at')
+            ->get();
+        foreach ($points as $point) {
+            if ($point->data) {
+                $point->data = json_decode($point->data, $_assoc);
+            }
+        }
+        return $points;
+    }
+
+    public static function getPlanPointsOfCategory(Client $_patient, String $_category, Note $_note, $_assoc = false) {
+        $points = Point
+            ::where('client_id', $_patient->id)
+            ->where('category', $_category)
+            ->where('is_removed_due_to_entry_error', false)
+            ->where(function ($query1) use ($_note) {
+                $query1
+                    ->where('is_removed', false)
+                    ->orWhere(function ($query2) use ($_note) {
+                        $query2->where('is_removed', true)
+                            ->where('removed_in_note_id', $_note->id);
+                    });
+            })
+            ->orderBy('created_at')
+            ->get();
+        foreach ($points as $point) {
+            if ($point->data) {
+                $point->data = json_decode($point->data, $_assoc);
+            }
+        }
+        return $points;
+    }
+
+    public static function getPointsOfCategory(Client $_patient, String $_category, $_assoc = false) {
+        $points = Point
+            ::where('client_id', $_patient->id)
+            ->where('category', $_category)
+            ->where('is_removed', false)
+            ->orderBy('created_at')
+            ->get();
+        foreach ($points as $point) {
+            if ($point->data) {
+                $point->data = json_decode($point->data, $_assoc);
+            }
+        }
+        return $points;
+    }
+}

+ 29 - 0
app/Models/Pro.php

@@ -14,6 +14,7 @@ class Pro extends Model
 
     public function displayName() {
         $name = [];
+        if(!empty($this->name_display)) return $this->name_display;
         if(!empty($this->name_last)) $name[] = $this->name_last;
         if(!empty($this->name_first)) $name[] = $this->name_first;
         if(!count($name)) {
@@ -32,6 +33,11 @@ class Pro extends Model
         return strtolower(implode("", $characters));
     }
 
+    public function debitBills()
+    {
+        return $this->hasMany(Bill::class, 'debit_pro_id');
+    }
+
     public function cmBills()
     {
         return $this->hasMany(Bill::class, 'cm_pro_id');
@@ -43,6 +49,20 @@ class Pro extends Model
         return $this->hasMany(Bill::class, 'hcp_pro_id');
     }
 
+    public function teamsWhereAssistant()
+    {
+        return $this->hasMany(ProTeam::class, 'assistant_pro_id', 'id');
+    }
+
+    public function isDefaultNA()
+    {
+        $numTeams = ProTeam::where('assistant_pro_id', $this->id)
+            ->where('is_active', true)
+            ->count();
+
+        return !!$numTeams;
+    }
+
     public function lastPayment() {
         return ProTransaction
             ::where('pro_id', $this->id)
@@ -120,6 +140,11 @@ class Pro extends Model
             ->orderBy('position_index', 'asc');
     }
 
+    public function visitTemplates() {
+        //TODO: use visit access
+        return VisitTemplate::all();
+    }
+
     public function currentWork() {
         return ProClientWork::where('pro_id', $this->id)->where('is_active', true)->first();
     }
@@ -576,4 +601,8 @@ class Pro extends Model
         return $this->hasOne(CompanyPro::class, 'id', 'default_company_pro_id');
     }
 
+    public function currentNotePickupForProcessing() {
+        return $this->hasOne(NotePickupForProcessing::class, 'id', 'current_note_pickup_for_processing_id');
+    }
+
 }

+ 25 - 0
app/Models/ProTeam.php

@@ -0,0 +1,25 @@
+<?php
+
+namespace App\Models;
+
+# use Illuminate\Database\Eloquent\Model;
+
+class ProTeam extends Model
+{
+    protected $table = 'pro_team';
+
+    public function mcp()
+    {
+        return $this->hasOne(Pro::class, 'id', 'mcp_pro_id');
+    }
+
+    public function assistant()
+    {
+        return $this->hasOne(Pro::class, 'id', 'assistant_pro_id');
+    }
+
+    public function rd()
+    {
+        return $this->hasOne(Pro::class, 'id', 'rd_pro_id');
+    }
+}

+ 22 - 0
app/Models/Segment.php

@@ -0,0 +1,22 @@
+<?php
+
+namespace App\Models;
+
+# use Illuminate\Database\Eloquent\Model;
+
+class Segment extends Model
+{
+    protected $table = 'segment';
+
+    public function segmentTemplate() {
+        return $this->hasOne(SegmentTemplate::class, 'id', 'segment_template_id');
+    }
+
+    public function note() {
+        return $this->hasOne(Note::class, 'id', 'note_id');
+    }
+
+    public function client() {
+        return $this->hasOne(Client::class, 'id', 'client_id');
+    }
+}

+ 11 - 0
app/Models/SegmentTemplate.php

@@ -0,0 +1,11 @@
+<?php
+
+namespace App\Models;
+
+# use Illuminate\Database\Eloquent\Model;
+
+class SegmentTemplate extends Model
+{
+    protected $table = 'segment_template';
+
+}

+ 10 - 0
app/Models/VisitTemplate.php

@@ -0,0 +1,10 @@
+<?php
+
+namespace App\Models;
+
+# use Illuminate\Database\Eloquent\Model;
+
+class VisitTemplate extends Model
+{
+    protected $table = 'visit_template';
+}

+ 2 - 1
composer.json

@@ -47,7 +47,8 @@
             "database/factories"
         ],
         "files": [
-            "app/Helpers/helpers.php"
+            "app/Helpers/helpers.php",
+            "app/Helpers/fdb.php"
         ]
     },
     "autoload-dev": {

+ 5 - 1
config/app.php

@@ -65,7 +65,11 @@ return [
 
     'hrm2_url' => env('HRM2_URL'),
 
-    'asset_version' => 6,
+    'asset_version' => 13,
+
+    'temp_dir' => env('TEMP_DIR'),
+
+    'stagfe6_url' => env('STAGFE6_URL'),
 
     /*
     |--------------------------------------------------------------------------

+ 15 - 0
config/database.php

@@ -78,6 +78,21 @@ return [
             'sslmode' => 'prefer',
         ],
 
+        'pgsql_fdb' => [
+            'driver' => 'pgsql',
+            'url' => env('DATABASE_URL'),
+            'host' => env('DB_HOST_FDB', '127.0.0.1'),
+            'port' => env('DB_PORT_FDB', '5432'),
+            'database' => env('DB_DATABASE_FDB', 'forge'),
+            'username' => env('DB_USERNAME_FDB', 'forge'),
+            'password' => env('DB_PASSWORD_FDB', ''),
+            'charset' => 'utf8',
+            'prefix' => '',
+            'prefix_indexes' => true,
+            'schema' => 'public',
+            'sslmode' => 'prefer',
+        ],
+
         'sqlsrv' => [
             'driver' => 'sqlsrv',
             'url' => env('DATABASE_URL'),

+ 347 - 0
fdb_notes.txt

@@ -0,0 +1,347 @@
+medSuggest
+https://docs.fdbhealth.com/display/MKDOCUS/Navigating+to+a+Routed+Medication+Route+Dosage+Form+and+Medication
+Retrieve the MED Medication Name ID (MED_NAME_ID) from the MED Medication Name Table (RMINMID1_MED_NAME) where the MED Medication Name (MED_NAME) equals the given drug.
+"SELECT med_name_id, med_name FROM rminmid1_med_name WHERE med_status_cd = '0' AND med_name ILIKE :term ORDER BY med_name",
+['term' => '%' . $term . '%']
+
+SELECT * FROM rminmid1_med_name LIMIT 5;
+ med_name_id |           med_name            | med_name_type_cd | med_status_cd 
+-------------+-------------------------------+------------------+---------------
+           1 | sertraline                    | 2                | 0
+           2 | Acetaminophen-Hydrocodone     | 1                | 1
+           3 | hydrocodone-carbinox-pseudoep | 2                | 3
+           4 | Phenylhistine DH              | 1                | 3
+           5 | denture care products         | 2                | 3
+
+
+
+routedMeds
+https://docs.fdbhealth.com/display/MKDOCUS/Navigating+to+a+Routed+Medication+Route+Dosage+Form+and+Medication
+Retrieve the Routed Medication ID (ROUTED_MED_ID) and MED Routed Medication Description (MED_ROUTED_MED_ID_DESC) values from the MED Routed Medication Table (RMIRMID1_ROUTED_MED) where the MED Medication Name (MED_NAME_ID) equals the value retrieved in the previous step and the MED Medication Status Code (MED_STATUS_CD) value equals 0 (active). 
+"SELECT routed_med_id, med_routed_med_id_desc FROM rmirmid1_routed_med WHERE med_status_cd = '0' AND med_name_id = :medNameID ORDER BY med_routed_med_id_desc",
+['medNameID' => $medNameID]
+ SELECT * FROM rmirmid1_routed_med  WHERE med_name_id = 1; 
+ routed_med_id | med_name_id | med_route_id | med_routed_med_id_desc | med_status_cd 
+---------------+-------------+--------------+------------------------+---------------
+             1 |           1 |           24 | sertraline oral        | 0
+
+
+routedDosages
+https://docs.fdbhealth.com/display/MKDOCUS/Navigating+to+a+Routed+Medication+Route+Dosage+Form+and+Medication
+Retrieve the MED Routed Dosage Form Med ID (ROUTED_DOSAGE_FORM_MED_ID) and from the MED Routed Dosage Form Medication Table (RMIDFID1_ROUTED_DOSE_FORM_MED) where the MED Routed Medication ID (ROUTED_MED_ID) equals the value retrieved in step 2 and th
+"SELECT routed_dosage_form_med_id, med_routed_df_med_id_desc FROM rmidfid1_routed_dose_form_med WHERE med_status_cd = '0' AND routed_med_id = :routedMedID ORDER BY med_routed_df_med_id_desc",
+['routedMedID' => $routedMedID]
+SELECT * FROM rmidfid1_routed_dose_form_med WHERE routed_med_id = 1;
+ routed_dosage_form_med_id | routed_med_id | med_dosage_form_id |  med_routed_df_med_id_desc  | med_status_cd 
+---------------------------+---------------+--------------------+-----------------------------+---------------
+                         1 |             1 |                 81 | sertraline tablet           | 0
+                     20735 |             1 |                 10 | sertraline oral concentrate | 0
+
+
+meds
+https://docs.fdbhealth.com/display/MKDOCUS/Navigating+to+a+Routed+Medication+Route+Dosage+Form+and+Medication
+Retrieve the Medication Identifier (MEDID) and MED Medication Description (MED_MEDID_DESC) values from the MED Medication Table (RMIID1_MED) where the MED Routed Dosage Form Med ID (ROUTED_DOSAGE_FORM_MED_ID) equals the value retrieved in the previous step and the MED Medication Status Code (MED_STATUS_CD) value equals 0 (active).
+"SELECT medid, med_medid_desc, gcn_seqno FROM rmiid1_med WHERE med_status_cd = '0' AND routed_dosage_form_med_id = :dosageFormMedId ORDER BY med_medid_desc",
+['dosageFormMedId' => $dosageFormMedId]
+\d rmiid1_med
+Table "public.rmiid1_med"
+          Column           |         Type          | Collation | Nullable | Default 
+---------------------------+-----------------------+-----------+----------+---------
+ medid                     | numeric(8,0)          |           | not null | 
+ routed_dosage_form_med_id | numeric(8,0)          |           | not null | 
+ med_strength              | character varying(15) |           |          | 
+ med_strength_uom          | character varying(15) |           |          | 
+ med_medid_desc            | character varying(70) |           | not null | 
+ gcn_seqno                 | numeric(6,0)          |           | not null | 
+ med_gcnseqno_assign_cd    | character varying(1)  |           | not null | 
+ med_name_source_cd        | character varying(1)  |           | not null | 
+ med_ref_fed_legend_ind    | character varying(1)  |           | not null | 
+ med_ref_dea_cd            | character varying(1)  |           | not null | 
+ med_ref_multi_source_cd   | character varying(1)  |           | not null | 
+ med_ref_gen_drug_name_cd  | character varying(1)  |           | not null | 
+ med_ref_gen_comp_price_cd | character varying(1)  |           | not null | 
+ med_ref_gen_spread_cd     | character varying(1)  |           | not null | 
+ med_ref_innov_ind         | character varying(1)  |           | not null | 
+ med_ref_gen_thera_equ_cd  | character varying(1)  |           | not null | 
+ med_ref_desi_ind          | character varying(1)  |           | not null | 
+ med_ref_desi2_ind         | character varying(1)  |           | not null | 
+ med_status_cd             | character varying(1)  |           | not null | 
+ generic_medid             | numeric(8,0)          |           |          |
+
+sideEffects
+https://docs.fdbhealth.com/display/MKDOCUS/Retrieving+a+List+of+Side+Effects
+-- Query the GCN_SEQNO column of the SIDE GCN_SEQNO/Drug Side Effect Code Relation Table (RSIDEGC0_GCNSEQNO_LINK) using the drug’s Clinical Formulation ID (GCN_SEQNO) value to retrieve all of its related SIDE Side Effects Code (SIDE) values.
+-- Query the SIDE column of the SIDE Master Table (RSIDEMA3_MSTR) using each SIDE value from the previous step to retrieve the following columns:
+	-- SIDE Frequency of Occurrence Code (SIDE_FREQ)
+	-- SIDE Severity Code (SIDE_SEV)
+	-- FML Disease Identifier (DXID)
+-- Follow the process described in the FML module’s Finding DXID Descriptions and Synonyms application to find each DXID value’s Primary Layman Name.
+SELECT r1.side, sm.side_freq, sm.side_sev, sm.dxid, dx.dxid_desc56 
+FROM rsidegc0_gcnseqno_link r1 
+    JOIN rsidema3_mstr sm ON r1.side = sm.side
+    JOIN rfmldx0_dxid dx ON sm.dxid = dx.dxid
+WHERE r1.gcn_seqno = :gcnSeqNo
+ORDER BY sm.side_sev DESC, sm.side_freq ASC
+['gcnSeqNo' => $gcnSeqNo]
+-- get a drug(routed dosage med) gcn_seqno 
+SELECT gcn_seqno FROM rmiid1_med WHERE routed_dosage_form_med_id  = 20735;
+ gcn_seqno 
+-----------
+     46230
+
+-- get side effects for the genseq
+SELECT * FROM rsidegc0_gcnseqno_link WHERE gcn_seqno = 46230;
+ gcn_seqno | side 
+-----------+------
+     46230 |  560
+     46230 | 2451
+
+
+-- get side effect details 
+SELECT * FROM RSIDEMA3_MSTR WHERE side = 560;
+ side | side_sn |   fdbdx   | side_freq | side_sev | side_viscd | side_labcd | side_phys | side_hyper | dxid  
+------+---------+-----------+-----------+----------+------------+------------+-----------+------------+-------
+  560 |       0 | 03.276100 | 2         | 1        | 2          | 1          | 1         |            |   736
+  560 |       1 | 05.296000 | 2         | 1        | 1          | 0          | 1         |            |   950
+  560 |       2 | 05.296010 | 2         | 1        | 1          | 0          | 1         |            |   951
+  560 |       3 | 05.300007 | 2         | 0        | 1          | 0          | 0         |            | 14664
+  560 |       4 | 05.300906 | 2         | 1        | 1          | 0          | 1         |            |   985
+  560 |       5 | 05.302700 | 0         | 1        | 1          | 0          | 1         |            |   992
+  560 |       6 | 05.302701 | 0         | 1        | 1          | 0          | 1         |            |   993
+  560 |       7 | 05.307900 | 1         | 0        | 1          | 0          | 0         |            |  1018
+
+-- side_feq dictionary 
+1 = Incidence less frequent
+0 = Incidence more frequent
+2 = Incidence rare or very rare
+
+-- side_sev dictionary
+0 = “less severe” if it is non-threatening (such as constipation)
+1 = “severe” if it may be life-threatening (such as agranulocytosis)
+
+-- get the description for a side effect using  dxid 
+SELECT * FROM rfmldx0_dxid WHERE dxid = 736;
+ dxid | dxid_desc56  | dxid_desc100 | dxid_status |   fdbdx   | dxid_disease_duration_cd 
+------+--------------+--------------+-------------+-----------+--------------------------
+  736 | hyponatremia | hyponatremia | 0           | 03.276100 | 3
+
+
+geriatricPrecautions
+https://docs.fdbhealth.com/display/MKDOCUS/Application%3A+Screening+a+Drug+for+Geriatric+Precautions
+-- Select Geriatric Precaution Code (GERI_CODE) from the GERI GCN_SEQNO Link Table (RGERIGC0_GERI_GCNSEQNO_LINK) where the Clinical Formulation ID (GCN_SEQNO) column equals the Clinical Formulation ID (GCN_SEQNO) of the drug to screen.
+-- Select GERI precautions information from the Geriatric Precautions Master Table (RGERIMA1_GERI_MSTR) where the GERI_CODE column equals the GERI_CODE value from the previous step.
+SELECT r1.geri_code, gm.geri_sl, gm.geri_desc, gm.geri_narrative
+FROM rgerigc0_geri_gcnseqno_link r1 
+JOIN rgerima1_geri_mstr gm ON r1.geri_code = gm.geri_code
+WHERE r1.gcn_seqno = :gcnSeqNo
+ORDER BY gm.geri_desc
+['gcnSeqNo' => $gcnSeqNo]
+-- select geriatricPrecautions based for a given drug formulation code 
+SELECT * FROM RGERIGC0_GERI_GCNSEQNO_LINK WHERE gcn_seqno = 46230 LIMIT 5 ;
+ gcn_seqno | geri_code 
+-----------+-----------
+     46230 |       831
+-- get the meaning of the geri_code 
+SELECT geri_code, geri_desc, geri_narrative FROM RGERIMA1_GERI_MSTR WHERE geri_code = 831;
+ geri_code | geri_desc  |                                                                                                                            geri_narrative                                                                                                                             
+-----------+------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------
+       831 | Sertraline | Hepatic-Mild hepatic impairment of aging may predispose the elderly to increased serum levels and increased adverse events.  Endocrine-May exacerbate or cause SIADH
+ or hyponatremia. Monitor sodium level closely when starting or changing dosages in older adults.
+
+
+indications
+https://docs.fdbhealth.com/display/MKDOCUS/Retrieving+a+Drug%27s+List+of+Indications
+Indications refers to the use of that drug for treating a particular disease
+-- Retrieve the INDM Indications Code (INDCTS) associated to the drug product’s Clinical Formulation ID (GCN_SEQNO) using the INDM GCN_SEQNO/Drug Indications Code Relation Table (RINDMGC0_INDCTS_GCNSEQNO_LINK).
+-- For each Clinical Formulation ID (GCN_SEQNO)/INDCTS combination retrieved in step 2, retrieve the following columns from the INDM Master Table (RINDMMA2_INDCTS_MSTR):
+	-- INDM Sequence Number (INDCTS_SN)
+	-- INDM Labeled Code (INDCTS_LBL)
+	-- FML Disease Identifier (DXID)
+	-- INDM Proxy Indicator (PROXY_IND)
+-- Get the description from https://docs.fdbhealth.com/display/MKDOCUS/Finding+DXID+Descriptions+and+Synonyms
+	-- For DxID 00000595’s Primary Professional Name, find its associated FML 56-character Description column (DXID_DESC56) and FML 100-character Description column (DXID_DESC100) in the FML Disease Identifier (DxID) Table (RFMLDX0_DXID).
+SELECT r1.indcts, r2.indcts_sn, r2.indcts_lbl, r2.dxid, r2.proxy_ind, r3.dxid_desc56
+FROM rindmgc0_indcts_gcnseqno_link r1 
+    JOIN rindmma2_indcts_mstr r2 ON r1.indcts = r2.indcts
+    JOIN rfmldx0_dxid r3 ON r2.dxid = r3.dxid
+WHERE r1.gcn_seqno = :gcnSeqNo
+ORDER BY r3.dxid_desc56
+['gcnSeqNo' => $gcnSeqNo]
+-- Select indications for a given gcn_seqno 
+SELECT * FROM RINDMGC0_INDCTS_GCNSEQNO_LINK WHERE gcn_seqno = 46230;
+ gcn_seqno | indcts 
+-----------+--------
+     46230 |    201
+-- get the details of the indicts 
+SELECT * FROM RINDMMA2_INDCTS_MSTR WHERE indcts = 201 AND proxy_ind <> 'Y' LIMIT 5;
+ indcts | indcts_sn | indcts_lbl |   fdbdx   | dxid  | proxy_ind | pred_code 
+--------+-----------+------------+-----------+-------+-----------+-----------
+    201 |         0 | U          | 05.296500 | 12862 | N         | 3
+    201 |         1 | U          | 05.298001 |  8464 | N         | 3
+    201 |         2 | L          | 05.300010 |   970 | N         | 2
+    201 |         3 | L          | 05.300230 |   975 | N         | 2
+    201 |         4 | L          | 05.300300 |   976 | N         | 3
+NB: to remove Non-FDA approved, add where indcts_lbl <> 'U'; //U == unlabeled
+-- get the meaning of DXIDs 
+SELECT * FROM RFMLDX0_DXID WHERE dxid IN (970, 975, 976);
+ dxid |          dxid_desc56          |         dxid_desc100          | dxid_status |   fdbdx   | dxid_disease_duration_cd 
+------+-------------------------------+-------------------------------+-------------+-----------+--------------------------
+  970 | panic disorder                | panic disorder                | 0           | 05.300010 | 1
+  975 | social phobia                 | social phobia                 | 0           | 05.300230 | 2
+  976 | obsessive-compulsive disorder | obsessive-compulsive disorder | 0           | 05.300300 | 2
+
+
+contraindications
+https://docs.fdbhealth.com/display/MKDOCUS/Retrieving+a+List+of+Drug+Contraindications
+-- Get drug ddxcn from rddcmrm0_routed_med_link
+-- Retrieve the FML Disease Identifier (DXID) values associated with DDXCN 50225 from the DDCM Master Table (RDDCMMA1_CONTRA_MSTR).
+-- Retrieve the FML 100-Character Description (DXID_DESC100) for each DXID value using the FML Disease Identifier (DxID) Table (RFMLDX0_DXID).
+SELECT r1.ddxcn, r2.dxid, r2.ddxcn_sl, r3.dxid_desc56
+FROM rddcmrm0_routed_med_link r1 
+    JOIN rddcmma1_contra_mstr r2 ON r1.ddxcn = r2.ddxcn
+    JOIN rfmldx0_dxid r3 ON r2.dxid = r3.dxid
+WHERE r1.routed_med_id = :routedMedID
+ORDER BY r2.ddxcn_sl
+['routedMedID' => $routedMedID]
+
+-- get drug disease contraindications for a given routed_med_id 
+SELECT * FROM RDDCMRM0_ROUTED_MED_LINK  WHERE routed_med_id = 1;
+ routed_med_id | ddxcn 
+---------------+-------
+             1 | 50005
+-- get the details of ddxcn 
+SELECT * FROM RDDCMDD0_CONTRA_DRUG_DESC WHERE ddxcn = 50005;
+ ddxcn | ddxcn_drug_desc 
+-------+-----------------
+ 50005 | SERTRALINE
+
+-- get dxid associated with the ddxcn (get disease id associated with the contraindications)
+SELECT * FROM RDDCMMA1_CONTRA_MSTR WHERE ddxcn = 50005; 
+ddxcn | ddxcn_sn |   fdbdx   | ddxcn_sl |         ddxcn_ref          | dxid  
+-------+----------+-----------+----------+----------------------------+-------
+ 50005 |        0 | 03.276100 | 3        | ZOLOFT PI, 12/2016         |   736
+ 50005 |        1 | 03.253600 | 3        | ZOLOFT PI, 12/2016         |   624
+ 50005 |        2 | 04.286906 | 3        | ZOLOFT PI, 12/2016         |   867
+ 50005 |        3 | 05.296700 | 3        | ZOLOFT PI, 12/2016         |   954
+ 50005 |        4 | 05.300906 | 2        | MEDWATCH, 3/04, PI 5/14    |   985
+ 50005 |        5 | 09.573900 | 2        | ZOLOFT PI, 12/2016         |  2202
+
+-- get human readable meanings of the dxid 
+SELECT * FROM RFMLDX0_DXID WHERE dxid IN (736,624,867,954,985,2202);
+ dxid |        dxid_desc56         |        dxid_desc100        | dxid_status |   fdbdx   | dxid_disease_duration_cd 
+------+----------------------------+----------------------------+-------------+-----------+--------------------------
+  624 | SIADH syndrome             | SIADH syndrome             | 0           | 03.253600 | 3
+  736 | hyponatremia               | hyponatremia               | 0           | 03.276100 | 3
+  867 | increased risk of bleeding | increased risk of bleeding | 0           | 04.286906 | 2
+  954 | bipolar disorder           | bipolar disorder           | 0           | 05.296700 | 2
+  985 | suicidal ideation          | suicidal ideation          | 0           | 05.300906 | 3
+ 2202 | disease of liver           | disease of liver           | 0           | 09.573900 | 2
+
+
+dxSuggest
+https://docs.fdbhealth.com/display/MKDOCUS/Finding+DXID+Descriptions+and+Synonyms
+-- For DxID 00000595’s Primary Professional Name, find its associated FML 56-character Description column (DXID_DESC56) and FML 100-character Description column (DXID_DESC100) in the FML Disease Identifier (DxID) Table (RFMLDX0_DXID).
+-- For DxID 00000595’s Professional Synonyms, find its associated FML 56-character Synonym Description (DXID_SYN_DESC56) and FML 100-character Synonym Description (DXID_SYN_DESC100) in the FML Disease Identifier (DxID) Synonym Table (RFMLSYN0_DXID_SYN). Specify a value of 01 for the FML Name Type Code (DXID_SYN_NMTYP) to signify that you wish to retrieve this DxID’s Professional Synonyms.
+-- i.e search where term matches in the main table (rfmldx0_dxid) and in the synonyms table (rfmlsyn0_dxid_syn) on both 56 and 100 character descriptions
+SELECT distinct(r1.dxid), r1.dxid_desc56 
+FROM rfmldx0_dxid r1
+JOIN rfmlsyn0_dxid_syn r2 ON r1.dxid = r2.dxid
+WHERE (r1.dxid_desc56 ILIKE :term OR r1.dxid_desc100 ILIKE :term OR r2.dxid_syn_desc56 ILIKE :term OR r2.dxid_syn_desc100 ILIKE :term)
+ORDER BY r1.dxid_desc56
+['term' => '%' . $term . '%']
+-- DX has 
+	- Primary Professional Name: one and only one - RFMLDX0_DXID
+	RFMLSYN0_DXID_SYN
+	- Professional Synonym: zero, one, or many -  dxid_syn_nmtyp = 01
+	- Primary Layman Name: zero, one, or many - dxid_syn_nmtyp = 02
+	- Layman Synonym: zero, one, or many - dxid_syn_nmtyp = 03
+	- Abbreviation: zero, one, or many - dxid_syn_nmtyp = 04
+ SELECT * FROM RFMLDX0_DXID WHERE dxid = '595';
+ dxid |       dxid_desc56        |       dxid_desc100       | dxid_status |   fdbdx   | dxid_disease_duration_cd 
+------+--------------------------+--------------------------+-------------+-----------+--------------------------
+  595 | type 1 diabetes mellitus | type 1 diabetes mellitus | 0           | 03.250010 | 2
+
+-- get synonyms: 
+ SELECT * FROM RFMLSYN0_DXID_SYN WHERE dxid = 595 AND dxid_syn_nmtyp = '01';
+ dxid_synid | dxid | dxid_syn_nmtyp |           dxid_syn_desc56           |          dxid_syn_desc100           | dxid_syn_status 
+------------+------+----------------+-------------------------------------+-------------------------------------+-----------------
+        384 |  595 | 01             | juvenile diabetes                   | juvenile diabetes                   | 0
+        387 |  595 | 01             | insulin-dependent DM                | insulin-dependent DM                | 0
+        388 |  595 | 01             | insulin-dependent diabetes mellitus | insulin-dependent diabetes mellitus | 0
+        389 |  595 | 01             | ketosis-prone diabetes mellitus     | ketosis-prone diabetes mellitus     | 0
+        390 |  595 | 01             | ketosis-prone diabetes              | ketosis-prone diabetes              | 0
+        391 |  595 | 01             | juvenile-onset diabetes             | juvenile-onset diabetes             | 0
+        392 |  595 | 01             | juvenile-onset diabetes mellitus    | juvenile-onset diabetes mellitus    | 0
+        393 |  595 | 01             | juvenile onset DM                   | juvenile onset DM                   | 0
+        394 |  595 | 01             | type I diabetes mellitus            | type I diabetes mellitus            | 0
+        395 |  595 | 01             | diabetes mellitus type 1            | diabetes mellitus type 1            | 0
+        396 |  595 | 01             | ketosis-prone DM                    | ketosis-prone DM                    | 0
+      58331 |  595 | 01             | insulin dependent diabetes mellitus | insulin dependent diabetes mellitus | 0
+      58407 |  595 | 01             | immune mediated diabetes mellitus   | immune mediated diabetes mellitus   | 0
+
+
+allergySuggest
+https://docs.fdbhealth.com/display/MKDOCUS/Recording+Patient+Allergy+Information
+-- Query the DAM Allergen Concept ID Description column (DAM_CONCEPT_ID_DESC) in the RDAMAPM0_ALRGN_PICKLIST_MSTR table or the RDAMCA0_CONCEPT table to find all entries with the description “carbamates."
+SELECT r1.dam_concept_id, r1.dam_concept_id_typ, r1.dam_concept_id_desc
+FROM rdamca0_concept r1
+WHERE (r1.dam_concept_id_desc ILIKE :term)
+ORDER BY r1.dam_concept_id_desc
+
+
+drugDrugInteraction
+https://docs.fdbhealth.com/display/MKDOCUS/Screening+for+Active+and+Inactive+Ingredient+Drug-Drug+Interactions
+
+drugCoadministration
+https://docs.fdbhealth.com/display/MKDOCUS/Displaying+Coadministration+Text
+
+duplicateTherapy
+https://docs.fdbhealth.com/display/MKDOCUS/Detecting+Therapeutic+Class+Duplications
+-- Retrieve the Routed Medication ID (ROUTED_MED_ID) in the DPT Routed Medication ID Table(rmirmid1_routed_med), or Routed Generic Identifier (ROUTED_GEN_ID) in the DPT Routed Generic Table, or Clinical Formulation ID (GCN_SEQNO) in the DPT GCN_SEQNO Table for the newly prescribed (prospective) drug and for each drug in the patient profile (profiled drugs).
+-- Retrieve the associated DPT Class Identifiers (DPT_CLASS_ID) from the DPT Class Table (RDPTCL0_CLASS_ID) for each prospective drug and each profiled drug.
+-- Compare the DPT_CLASS_IDs and retrieve the DPT Class Description (DPT_CLASS_DESC) record from the RDPTCL0_CLASS_ID table when Duplicate Therapy Class matches occur.
+-- Compare the number of times that a match of a given class is returned with the DPT Duplication Allowance (DPT_ALLOWANCE) from the RDPTCL0_CLASS_ID table. If the number of matches exceeds the DPT_ALLOWANCE value, a duplicate therapy exists. In most instances, the duplication allowance is zero. Programming for a duplication allowance of one or more should occur only for drugs in the same class that are used concurrently, per accepted medical practice.
+
+=====================================================================================================
+Get drugs used to treat a given condition 
+-- get dxid for the condition eg. 'social phobia'
+SELECT * FROM RFMLDX0_DXID WHERE dxid_desc56 ILIKE 'social%';
+ dxid |  dxid_desc56  | dxid_desc100  | dxid_status |   fdbdx   | dxid_disease_duration_cd 
+------+---------------+---------------+-------------+-----------+--------------------------
+  975 | social phobia | social phobia | 0           | 05.300230 | 2
+
+-- get indcts for the condition 
+SELECT DISTINCT(indcts) FROM RINDMMA2_INDCTS_MSTR WHERE dxid = 975 AND proxy_ind <> 'Y' AND indcts_lbl <> 'U';
+ indcts 
+--------
+    201
+   1006
+   1457
+   1695
+
+-- get clinical formulations (gcn_seqno) for the above indcts 
+SELECT * FROM RINDMGC0_INDCTS_GCNSEQNO_LINK WHERE indcts IN (201,1006,1457,1695);
+ gcn_seqno | indcts 
+-----------+--------
+     46222 |   1006
+     46223 |   1006
+     46224 |   1006
+     46225 |   1006
+     46226 |   1006
+....
+
+-- get drugs that contain this gcn_seqno 
+SELECT medid, med_medid_desc, gcn_seqno FROM rmiid1_med WHERE gcn_seqno IN (SELECT gcn_seqno FROM RINDMGC0_INDCTS_GCNSEQNO_LINK WHERE indcts IN (201,1006,1457,1695));
+SELECT medid, med_medid_desc, gcn_seqno FROM rmiid1_med WHERE gcn_seqno IN (SELECT gcn_seqno FROM RINDMGC0_INDCTS_GCNSEQNO_LINK WHERE indcts IN (201,1006,1457,1695));
+ medid  |                    med_medid_desc                     | gcn_seqno 
+--------+-------------------------------------------------------+-----------
+ 157825 | paroxetine ER 37.5 MG tablet,extended release 24 hr   |     50138
+ 159557 | venlafaxine ER 37.5 mg capsule,extended release 24 hr |     46403
+ 160594 | venlafaxine ER 75 mg capsule,extended release 24 hr   |     46404
+ 162880 | paroxetine 10 mg tablet                               |     46222
+ 165384 | Effexor XR 75 mg capsule,extended release             |     46404
+ 166110 | Paxil CR 37.5 MG tablet,extended release              |     50138
+ 182739 | Effexor XR 37.5 mg capsule,extended release           |     46403
+ 183163 | Paxil 20 mg tablet                                    |     46223
+ 184142 | Paxil 10 mg/5 mL oral suspension                      |     46226
+ 187550 | sertraline 100 mg tablet                              |     46229

+ 231 - 16
public/css/style.css

@@ -41,6 +41,9 @@
 .text-warning-mellow {
     color: #d8a714!important;
 }
+.bg-warning-mellow {
+    background-color: #ffc10777 !important;
+}
 .text-link {
     color: rgb(13, 89, 175) !important;
 }
@@ -292,9 +295,15 @@ body>nav.navbar {
 .mcp-theme-1 .width-50px {
     width: 50px !important;
 }
+.mcp-theme-1 .width-60px {
+    width: 60px !important;
+}
 .mcp-theme-1 .width-70px {
     width: 70px !important;
 }
+.mcp-theme-1 .min-width-70px {
+    min-width: 70px !important;
+}
 .mcp-theme-1 .width-90px {
     width: 90px !important;
 }
@@ -381,6 +390,10 @@ body>nav.navbar {
 .ql-editor ul > li::before {
     content: '';
 }
+.m-neg-3 {
+    margin-left: -1rem;
+    margin-right: -1rem;
+}
 .m-neg-4 {
     margin-left: -1.25rem;
     margin-right: -1.25rem;
@@ -414,6 +427,9 @@ body>nav.navbar {
     background: #f6f9fc;
     cursor: pointer;
 }
+[data-non-segment-section]:hover {
+    background: #f6f9fc;
+}
 .note-signed-by-hcp .note-section:not(.edit):hover {
     background: #f6f9fc;
     cursor: auto;
@@ -480,6 +496,7 @@ input.search_field, textarea.search_field {
         z-index: 8;
         height: calc(100% - 55px);
         overflow-y: overlay;
+        padding-bottom: 4rem;
     }
     .main-row {
         padding-left: 180px;
@@ -545,6 +562,12 @@ input.search_field, textarea.search_field {
     min-width: calc(100% - 0.5rem);
     right: 0.5rem;
 }
+[stag-suggest-bottom-left]~.stag-suggestions-container .suggestions-outer {
+    bottom: 30px;
+    left: 0;
+    top: auto;
+    right: auto;
+}
 .suggestions-outer .suggest-item, .suggestions-outer .no-suggest-items {
     padding: 0.25rem 0.5rem;
     text-decoration: none;
@@ -582,8 +605,8 @@ input.search_field, textarea.search_field {
     font-weight: bold !important;
     color: #000 !important;
 }
-#caremonth-measurements-calendar table.table-condensed td[has-events],
-#caremonth-measurements-calendar td.has-events a {
+.caremonth-measurements-calendar table.table-condensed td[has-events],
+.caremonth-measurements-calendar td.has-events a {
     background: #c5e4ff !important;
     font-weight: bold !important;
     color: #000 !important;
@@ -1017,6 +1040,12 @@ body .node input[type="number"] {
     padding: 0.75rem;
     min-height: 220px;
 }
+.stag-popup.overflow-visible>.stag-popup-content {
+    overflow: visible;
+}
+.stag-popup.min-height-unset>form {
+    min-height: unset !important;
+}
 .stag-popup.wide>form, .stag-popup.wide>.stag-popup-content {
     width: calc(100% - 4rem);
 }
@@ -1262,6 +1291,9 @@ span.select2-container.select2-container--default.select2-container--open {
 .fc .fc-highlight {
     background: rgba(188, 232, 241, 0.6) !important;
 }
+.fc .fc-day-past {
+    background: #e7e7e7 !important;
+}
 .fc .add-overlay {
     padding: 1px 4px;
     display: inline-block;
@@ -1499,6 +1531,7 @@ button.note-templates-trigger-assessment {
     pointer-events: none;
     transition: opacity 0.3s ease;
     z-index: 2;
+    top: 0;
 }
 .appointment-confirmation-history-trigger:hover .appointment-confirmation-history {
     opacity: 1;
@@ -1509,15 +1542,15 @@ button.note-templates-trigger-assessment {
     overflow: hidden;
     text-overflow: ellipsis;
 }
-/*.on-hover-text-reveal:hover {
+.on-hover-text-reveal:hover {
     white-space: normal;
     overflow: unset;
     text-overflow: unset;
-}*/
+}
 .collapsible-tbody.collapsed {
     display: none;
 }
-#send-fax-pdf-preview {
+#send-fax-pdf-preview, #transmit-pdf-preview {
     max-height: 350px;
     overflow: auto;
     box-shadow: 0 0 2px #ccc;
@@ -1666,24 +1699,32 @@ th.only-screen, td.only-screen {
 .stag-table-container-lg>table{
     min-width: 1450px;
 }
+.stag-table-container.stag-table-container-no-x-scroll {
+    overflow-x: hidden !important;
+}
+
+.stag-fc-container .fc-toolbar-title .tz-display {
+    font-size: inherit;
+    font-family: inherit;
+}
 
-#caremonth-measurements-calendar .fc-event.m-weight {
+.caremonth-measurements-calendar .fc-event.m-weight {
     background: #38908f;
     color: #fff;
     padding-left: 5px;
     margin-bottom: 2px;
 }
-#caremonth-measurements-calendar .fc-event.m-bp {
+.caremonth-measurements-calendar .fc-event.m-bp {
     background: #5e96ae;
     color: #fff;
     padding-left: 5px;
     margin-bottom: 2px;
 }
-#caremonth-measurements-calendar .fc-event.m-weight *,
-#caremonth-measurements-calendar .fc-event.m-bp *{
+.caremonth-measurements-calendar .fc-event.m-weight *,
+.caremonth-measurements-calendar .fc-event.m-bp *{
     font-size: 10px !important;
 }
-#caremonth-measurements-calendar .fc-daygrid-event-dot {
+.caremonth-measurements-calendar .fc-daygrid-event-dot {
     display: none;
 }
 
@@ -1691,16 +1732,13 @@ th.only-screen, td.only-screen {
     width: 100%;
     border: 0 !important;
 }
-#caremonth-measurements-calendar>.ui-datepicker-inline {
+.caremonth-measurements-calendar>.ui-datepicker-inline {
     width: 100%;
 }
-#caremonth-measurements-calendar .ui-datepicker-prev,
-#caremonth-measurements-calendar .ui-datepicker-next {
+.caremonth-measurements-calendar .ui-datepicker-prev,
+.caremonth-measurements-calendar .ui-datepicker-next {
     display: none;
 }
-#caremonth-measurements-calendar {
-    pointer-events: none !important;
-}
 #simpleSMSReminderComponent input[type="time"] {
     max-width: 90px;
     min-width: unset !important;
@@ -1871,4 +1909,181 @@ table.dashboard-stats-table th {
 }
 .min-height-500px {
     min-height: 500px;
+}
+.inline-html-container p {
+    margin-bottom: 0;
+}
+body.in-iframe>.navbar {
+    display: none !important;
+}
+body.in-iframe .stag-content {
+    padding-top: 0 !important;
+}
+body.in-iframe .main-row > .sidebar {
+    top: 0;
+    height: 100%;
+}
+.stag-popup .hide-inside-popup {
+    display: none !important;
+}
+.strike-through {
+    text-decoration: line-through;
+}
+
+/* visit-moe */
+[visit-moe] [url]:not([show]){
+    display: none;
+}
+[visit-moe] {
+    display: inline-block;
+}
+[visit-moe][relative] {
+    position: relative;
+}
+[visit-moe] [url]:not([show]) {
+    z-index: 99999;
+    position: absolute;
+    background-color: white;
+    padding: 10px;
+    border: 1px solid gray;
+}
+[visit-moe][fixed-center] [url]:not([show]) {
+    position: fixed !important;
+    top: 50% !important;
+    left: 50% !important;
+    width: 600px;
+    transform: translate(-50%, -50%) !important;
+}
+[visit-moe] [url][right] {
+    right: 0;
+    min-width: 200px;
+}
+[visit-moe][large] form, [visit-moe][large] [url] {
+    width: 450px;
+}
+[visit-moe][bottom] form {
+    bottom: 100%;
+}
+.note-container {
+    display: flex;
+    align-items: start;
+}
+.note-container .note-lhs-tree {
+    min-width: 220px;
+    max-width: 220px;
+    align-self: stretch;
+    border-right: 1px solid #ddd;
+    padding-top: 0.85rem;
+    height: 300px;
+    overflow: overlay;
+    max-height: calc(100vh - 55px);
+    background-color: #fff;
+}
+.note-container .note-lhs-tree.fixed {
+    position: fixed;
+    top: 55px;
+    max-height: calc(100vh - 55px) !important;
+    height: calc(100vh - 55px) !important;
+}
+.note-container .note-lhs-tree.fixed ~ .note-rhs-content {
+    margin-left: 220px;
+}
+.note-container .note-lhs-tree .note-tree-node.note-tree-heading>a {
+
+}
+.note-container .note-lhs-tree .note-tree-node>a {
+    display: block;
+    padding: 0.15rem 0;
+    padding-left: 0.75rem;
+    white-space: nowrap;
+    text-overflow: ellipsis;
+    overflow: hidden;
+    text-decoration: none;
+    color: #333;
+}
+.note-container .note-lhs-tree .note-tree-node>a:hover {
+    background-color: aliceblue;
+    color: #0d59af !important;
+}
+.note-container .note-lhs-tree .note-tree-node:hover>a,
+.note-container .note-lhs-tree .note-tree-node.hovered>a {
+    background-color: aliceblue;
+}
+.note-container .note-lhs-tree .note-tree-node.active>a {
+    font-weight: bold !important;
+    color: #0d59af !important;
+}
+.note-container .note-lhs-tree .note-tree-children>.note-tree-node>a {
+    padding-left: 2rem;
+}
+.note-container .note-lhs-tree .note-tree-children .note-tree-children>.note-tree-node>a {
+    padding-left: 4rem;
+}
+.note-container .note-rhs-content {
+    flex-grow: 1;
+}
+.spot-highlight {
+    background: aliceblue !important;
+}
+.on-click-menu [menu] {
+    position: absolute;
+    display: none;
+    top: 100%;
+    right: 0;
+    z-index: 1;
+}
+.zero-height {
+    height: 0 !important;
+    padding: 0 !important;
+    border: 0 !important;
+    overflow: hidden;
+}
+/*.note-section[data-segment-template-name="medrisk_vigilence"] {
+    position: fixed;
+    right: 0;
+    top: 55px;
+    width: 40px;
+    height: calc(100vh - 54px);
+    background: aliceblue;
+    padding: 0 !important;
+    border-left: 1px solid #ddd;
+    transition: width 0.1s ease;
+}*/
+.on-trigger-only,
+.on-content-only {
+    display: none !important;
+}
+.mrv-trigger .on-trigger-only,
+.mrv-content .on-content-only {
+    display: inherit !important;
+}
+.mrv-badge {
+    border-radius: 100%;
+    height: 24px;
+    width: 24px;
+    min-height: 24px;
+    min-width: 24px;
+    max-height: 24px;
+    max-width: 24px;
+    text-align: center;
+    font-weight: 400;
+    display: flex;
+    align-items: center;
+    justify-content: center;
+    background-color: #6457f9;
+    color: #fff;
+    opacity: 0.85;
+}
+.mrv-badge>span {
+    font-size: 10px !important;
+}
+.note-bottom-toolbar {
+    bottom: 0;
+}
+.note-bottom-toolbar .nbt-container:hover {
+    cursor: pointer;
+    background: #fff !important;
+}
+[open-in-stag-popup] * {
+    pointer-events: none;
 }

+ 8 - 3
public/js/mc.js

@@ -177,14 +177,14 @@ function onFastLoaded(_data, _href, _history) {
                 }
                 window.top.currentMcUrl = window.top.location.href;
 
-                let activeLeftNavLink = $('#sidebarMenu .nav-item>.nav-link.active').first();
+                /*let activeLeftNavLink = $('#sidebarMenu .nav-item>.nav-link.active').first();
                 if(activeLeftNavLink.length) {
                     activeLeftNavLink[0].scrollIntoView({
                         behavior: "smooth",
                         block: "nearest",
                         inline: "nearest"
                     });
-                }
+                }*/
             }, 0);
         }
         else {
@@ -231,7 +231,7 @@ function fastLoad(_href, _history = true, _useCache = true, _replaceState = fals
     if (_href === '') _href = '/';
 
     // push state
-    if (_history) {
+    if (_history && window.parent === window.top) {
         var target = _href;
         if (target.indexOf('//') !== -1) {
             target = target.split('//')[1];
@@ -248,6 +248,11 @@ function fastLoad(_href, _history = true, _useCache = true, _replaceState = fals
         }
     }
 
+    // dont show top nav if in iframe
+    if(window !== window.top && window.parent !== window.top) {
+        $('body').addClass('in-iframe');
+    }
+
     if (_useCache && !!fastCache[_href]) {
         onFastLoaded(fastCache[_href], _href, _history);
     } else {

+ 6 - 4
public/js/pro-suggest.js

@@ -19,7 +19,7 @@
     var returnedFunction = debounce(function (elem) {
         var term = elem.val();
         if (!!term && lastTerm !== term) {
-            $.get('/pro-suggest?term=' + $.trim(term), function (_data) {
+            $.get('/pro-suggest?term=' + $.trim(term) + '&type=' + elem.attr('provider-type'), function (_data) {
                 suggestionsOuter.html(_data).removeClass('d-none');
             });
             lastTerm = term;
@@ -95,15 +95,17 @@
             elem.next('.pro-suggest-input').remove();
             elem.next('.pro-suggestions-container').remove();
             let input = $('<input type="text" placeholder="Pro">').addClass('pro-suggest-input form-control form-control-sm').insertAfter(elem);
+            input.attr('provider-type', elem.attr('provider-type'));
             $('<div class="pro-suggestions-container position-relative">' +
                 '<div class="suggestions-outer pro-suggestions position-absolute d-none"></div>' +
                 '</div>').insertAfter(input);
             elem.hide();
 
-            if(!!elem.attr('data-pro-uid')) {
-                $.get('/pro-display-name/' + elem.attr('data-pro-uid'), function(_data) {
+            let proUid = elem.attr('data-pro-uid');
+            if(!!proUid) {
+                $.get('/pro-display-name/' + proUid, function(_data) {
                     input.val(_data).data('original', _data);
-                    elem.empty().append($('<option value="' + elem.attr('data-pro-uid') + '" selected/>').text(_data));
+                    elem.empty().append($('<option value="' + proUid + '" selected/>').text(_data));
                 });
             }
             else {

+ 22 - 0
public/js/show-on-click.js

@@ -0,0 +1,22 @@
+(function() {
+    function init() {
+        $(document)
+            .off('click.show-on-click', '.show-on-click')
+            .on('click.show-on-click', '.show-on-click', function(_e) {
+                if($(this).text() === $(this).attr('data-value')) {
+                    $(this).text('Click to view');
+                }
+                else {
+                    $(this).text($(this).attr('data-value'));
+
+                    // fire pro event
+                    $.post('/api/proEvent/create', {
+                        proUid: $(this).attr('data-pro-uid'),
+                        event: $(this).attr('data-event'),
+                    }, () => {}, 'json');
+                }
+                return false;
+            });
+    }
+    addMCInitializer('show-on-click', init);
+})();

+ 4 - 4
public/js/stag-popup.js

@@ -44,7 +44,7 @@ function closeStagPopup(_noEvent = false) {
         }
     }
     else {
-        if(popup.is('[update-parent]')) {
+        if(popup.is('[update-parent]') && !_noEvent) {
             if(stagPopupsQueue.length) {
                 refreshDynamicStagPopup();
             }
@@ -160,11 +160,11 @@ function hasResponseError(_data) {
             });
 
         $(document)
-            .off('click.open-in-stag-popup', 'a[open-in-stag-popup]')
-            .on('click.open-in-stag-popup', 'a[open-in-stag-popup]', function() {
+            .off('click.open-in-stag-popup', '[open-in-stag-popup]')
+            .on('click.open-in-stag-popup', '[open-in-stag-popup]', function() {
                 let trig = $(this);
                 openDynamicStagPopup(
-                    this.href,
+                    trig.attr('href'),
                     trig.attr('mc-initer'),
                     trig.attr('title'),
                     trig.is('[update-parent]'),

+ 191 - 0
public/js/stag-suggest.js

@@ -0,0 +1,191 @@
+(function () {
+    window.initStagSuggest = function () {
+
+        let suggestionsOuter = null;
+
+        const debounce = (func, wait) => {
+            let timeout;
+            return function executedFunction(...args) {
+                const later = () => {
+                    clearTimeout(timeout);
+                    func(...args);
+                };
+                clearTimeout(timeout);
+                timeout = setTimeout(later, wait);
+            };
+        };
+
+        var lastTerm = '';
+        var returnedFunction = debounce(function (elem) {
+            let term = elem.val();
+            if (!!term && lastTerm !== term) {
+                let ep = $(elem).attr('stag-suggest-ep');
+                $.get(ep + '?term=' + $.trim(term), function (_data) {
+
+                    /*
+                    expected return format:
+                    {
+                        success: true,
+                        data: [
+                            {
+                                x: ...,
+                                y: ...,
+                                text: ...    // "text" key is "mandatory"
+                            },
+                            {
+                                x: ...,
+                                y: ...,
+                                text: ...    // "text" key is "mandatory"
+                            },
+                            ...
+                        ]
+                    }
+                     */
+
+                    suggestionsOuter.empty();
+                    if(!hasResponseError(_data) && _data.data && _data.data.length) {
+                        for (let i = 0; i < _data.data.length; i++) {
+                            let item = $('<a native href="#" class="d-block suggest-item stag-suggest text-nowrap"/>');
+                            for(let x in _data.data[i]) {
+                                if(_data.data[i].hasOwnProperty(x) && x !== 'text') {
+                                    item.attr('data-' + x, _data.data[i][x]);
+                                }
+                            }
+                            item.data('suggest-data', _data.data[i]);
+                            item.html(_data.data[i].text);
+                            suggestionsOuter.append(item);
+                        }
+                    }
+                    else {
+                        suggestionsOuter.html('<span class="d-block no-suggest-items">No matches!</span>');
+                    }
+
+                    suggestionsOuter.removeClass('d-none');
+                }, 'json');
+                lastTerm = term;
+            } else {
+                suggestionsOuter.addClass('d-none');
+            }
+        }, 250);
+
+        function handleKeydown(elem, e) {
+            let term = $.trim(elem.val());
+            let activeItem = suggestionsOuter.find('.suggest-item.active');
+            switch (e.which) {
+                case 27:
+                    suggestionsOuter.addClass('d-none');
+                    return false;
+                case 38:
+                    if (activeItem.prev().length) {
+                        activeItem.prev()
+                            .addClass('active')
+                            .siblings().removeClass('active');
+                        activeItem = suggestionsOuter.find('.suggest-item.active');
+                        if (activeItem.length) {
+                            activeItem[0].scrollIntoView();
+                        }
+                    }
+                    return false;
+                case 40:
+                    if (activeItem.next().length) {
+                        activeItem.next()
+                            .addClass('active')
+                            .siblings().removeClass('active');
+                        activeItem = suggestionsOuter.find('.suggest-item.active');
+                        if (activeItem.length) {
+                            activeItem[0].scrollIntoView();
+                        }
+                    }
+                    return false;
+                case 13:
+                    if (activeItem.length) {
+                        activeItem.first().click();
+                    }
+                    return false;
+                default:
+                    if (!!term) {
+                        suggestionsOuter
+                            .html('<span class="d-block no-suggest-items">Searching...</span>')
+                            .removeClass('d-none');
+                        returnedFunction(elem);
+                    } else {
+                        suggestionsOuter.addClass('d-none');
+                    }
+                    break;
+            }
+        }
+
+        function handleKeypress(elem, e) {
+            var term = $.trim(elem.val());
+            if (!!term) {
+                suggestionsOuter
+                    .html('<span class="d-block no-suggest-items">Searching...</span>')
+                    .removeClass('d-none');
+                returnedFunction(elem);
+            } else {
+                suggestionsOuter.addClass('d-none');
+            }
+        }
+
+        $('[stag-suggest]:not([stag-suggest-initialized])').each(function () {
+            let elem = $(this);
+            elem.next('.stag-suggestions-container').remove();
+            $('<div class="stag-suggestions-container position-relative">' +
+                '<div class="suggestions-outer stag-suggestions position-absolute d-none"></div>' +
+                '</div>').insertAfter(elem);
+
+            elem
+                .off('keydown.stag-suggest')
+                .on('keydown.stag-suggest', function (e) {
+                    suggestionsOuter = $(this).next('.stag-suggestions-container').find('>.suggestions-outer');
+                    return handleKeydown($(this), e);
+                })
+                .off('keypress.stag-suggest')
+                .on('keypress.stag-suggest', function (e) {
+                    suggestionsOuter = $(this).next('.stag-suggestions-container').find('>.suggestions-outer');
+                    return handleKeypress($(this), e);
+                });
+
+            $(this).attr('stag-suggest-initialized', 1);
+        });
+
+        // on auto-suggest selection
+        $(document).off('click', '.suggest-item.stag-suggest');
+        $(document).on('click', '.suggest-item.stag-suggest', function () {
+
+            $('.suggestions-outer.stag-suggestions').addClass('d-none');
+
+            let data = $(this).data('suggest-data'),
+                label = $.trim($(this).text());
+
+            // set value
+            let input = $(this).closest('.position-relative').prev('[stag-suggest]');
+            input.val(label);
+            input.data('suggest-data', data);
+
+            let scope = input.attr('stag-suggest-scope');
+            if(!scope) scope = 'form';
+            scope = $(scope);
+
+            for(let x in data) {
+                if(data.hasOwnProperty(x)) {
+                    input.attr('data-' + x, data[x]);
+
+                    // auto-populate if there's a field matching data-name="x" in the scope
+                    if(scope.find('[data-name="' + x + '"]').length) {
+                        scope.find('[data-name="' + x + '"]').val(data[x]).trigger('change');
+                    }
+
+                }
+            }
+            input.trigger('input');
+            input.trigger('change');
+
+            input.trigger('stag-suggest-selected', [input, data]);
+
+            return false;
+        });
+
+    }
+    addMCInitializer('stag-suggest', window.initStagSuggest);
+})();

File diff suppressed because it is too large
+ 0 - 0
public/js/yemi.js


+ 213 - 13
resources/views/app/dashboard.blade.php

@@ -2,7 +2,7 @@
 
 @section('content')
 <div class="p-3">
-    <div class="m-0 mt-4">
+    <div class="">
         <div class="row mcp-theme-1" id="pro-dashboard-container" v-cloak>
             <div class="col-md-3 mcp-theme-1">
                 <div class="mb-4" v-show="tab==='appointments'">
@@ -33,10 +33,17 @@
                                     <th class="px-2 text-center">{{$keyNumbers['signedNotesWithoutBills']}}</th>
                                     <th class="pl-2"><a href="/practice-management/notes/without-bills">Signed notes without bills</a></th>
                                 </tr>
+                                @if(!$pro->isDefaultNA())
                                 <tr>
                                     <th class="px-2 text-center">{{$keyNumbers['pendingNotesToSign']}}</th>
                                     <th class="pl-2"><a href="/practice-management/notes/not-yet-signed">Pending notes to sign</a></th>
                                 </tr>
+                                @else
+                                <tr>
+                                    <th class="px-2 text-center">{{$keyNumbers['$pendingNotesToSignMCP']}}</th>
+                                    <th class="pl-2"><a href="/practice-management/dna-notes-pending-mcp-sign">Pending notes to sign (MCP)</a></th>
+                                </tr>
+                                @endif
                                 @if(!!$keyNumbers['pendingNotesToSignAllySigned'])
                                 <tr>
                                     <th class="px-2 text-center">{{$keyNumbers['pendingNotesToSignAllySigned']}}</th>
@@ -86,6 +93,16 @@
                                         <a href="/practice-management/rm-bills-to-sign">RM Bills to Sign</a>
                                     </th>
                                 </tr>
+                                @if($pro->pro_type === 'ADMIN')
+                                    <tr>
+                                        <th class="px-2 text-center">{{$keyNumbers['patientsWithoutCoverageInformation']}}</th>
+                                        <th class="pl-2"><a href="/practice-management/patients-without-coverage/without-coverage-information">Without coverage information</a></th>
+                                    </tr>
+                                    <tr>
+                                        <th class="px-2 text-center">{{$keyNumbers['patientsPendingCoverageVerification']}}</th>
+                                        <th class="pl-2"><a href="/practice-management/patients-without-coverage/pending-coverage-verification">Pending coverage verification</a></th>
+                                    </tr>
+                                @endif
                             </tbody>
                         </table>
                     </div>
@@ -154,7 +171,7 @@
                                 </tr> -->
                                 <tr>
                                     <th class="px-2">${{friendly_money($reimbursement['nextPaymentAmount'])}}</th>
-                                    <th class="pl-2">Processing</th>
+                                    <th class="pl-2"><a href="/practice-management/bills-under-processing">Processing</a></th>
                                 </tr>
                                 {{--
                                 <tr>
@@ -203,13 +220,99 @@
 
                 <div class="row">
                     <div class="col-6">
+
+                        <!-- Appointment Updates -->
+                        @if(count($proApptUpdates))
+                            <div class="mb-3 border rounded px-3 py-2 ack-container">
+                                <p class="pt-1 mb-2"><b>Appointment Updates</b></p>
+                                <table class="table table-sm table-hover table-bordered mb-0">
+                                    <thead>
+                                    <tr>
+                                        <th>Client</th>
+                                        <th>Appt. Date/Time</th>
+                                        <th>Status</th>
+                                        <th></th>
+                                    </tr>
+                                    </thead>
+                                    <tbody>
+                                        @foreach($proApptUpdates as $update)
+                                            <tr>
+                                                <td>{{$update->name_first}} {{$update->name_last}}</td>
+                                                <td>{{friendlier_date_time($update->start_time)}}</td>
+                                                <td>{{$update->status}}</td>
+                                                <td><a href="#" class="ack-pro-appt-update" data-uid="{{$update->uid}}">Acknowledge</a></td>
+                                            </tr>
+                                        @endforeach
+                                    </tbody>
+                                </table>
+                            </div>
+                        @endif
+
+                        @if(count($naApptUpdates))
+                            <div class="mb-3 border rounded px-3 py-2 ack-container">
+                                <p class="pt-1 mb-2"><b>Appointment Updates</b></p>
+                                <table class="table table-sm table-hover table-bordered mb-0">
+                                    <thead>
+                                    <tr>
+                                        <th>Client</th>
+                                        <th>Pro</th>
+                                        <th>Appt. Date/Time</th>
+                                        <th>Status</th>
+                                        <th></th>
+                                    </tr>
+                                    </thead>
+                                    <tbody>
+                                    @foreach($naApptUpdates as $update)
+                                        <tr>
+                                            <td>{{$update->name_first}} {{$update->name_last}}</td>
+                                            <td>{{$update->pro_name_first}} {{$update->pro_name_last}}</td>
+                                            <td>{{friendlier_date_time($update->start_time)}}</td>
+                                            <td>{{$update->status}}</td>
+                                            <td><a href="#" class="ack-na-appt-update" data-uid="{{$update->uid}}">Acknowledge</a></td>
+                                        </tr>
+                                    @endforeach
+                                    </tbody>
+                                </table>
+                            </div>
+                        @endif
+
                         <!-- new associations -->
                         @if(count($newMCPAssociations))
                             <div class="mb-3 border rounded px-3 py-2 ack-container">
                                 <p class="pt-1 mb-2"><b>New Patients</b></p>
                                 @foreach($newMCPAssociations as $assoc)
-                                    <div class="mb-1">You have been assigned as the MCP for
-                                        <a href="/patients/view/{{$assoc->patient->uid}}" class="d-inline-block width-150px">{{$assoc->patient->displayName()}}</a>.
+                                    <div class="d-flex align-items-start bg-light mb-2 px-2 py-1">
+                                        <div class="flex-grow-1">
+                                            You are now the MCP for
+                                            <a href="/patients/view/{{$assoc->patient->uid}}" class="">{{$assoc->patient->displayName()}}</a>
+                                            <?php $nextAppt = $assoc->patient->nextAppointment(); ?>
+                                            @if($nextAppt)
+                                                <div class="font-size-11">
+                                                    <span class="text-secondary font-size-11">Appt.</span>
+                                                    {{$nextAppt->pro->displayName()}}
+                                                    <span class="text-secondary font-size-11">on</span>
+                                                    {{friendlier_date_time($nextAppt->raw_date . ' ' . $nextAppt->raw_start_time)}}
+                                                </div>
+                                                @if($nextAppt->status === 'CREATED')
+                                                    <div class="text-warning-mellow font-weight-bold font-size-11 mt-1">
+                                                        <i class="fa fa-exclamation-triangle"></i>
+                                                        Confirmation pending
+                                                    </div>
+                                                @endif
+                                                @if($nextAppt->status === 'CONFIRMED')
+                                                    <div class="text-success font-weight-bold font-size-11 mt-1">
+                                                        <i class="fa fa-check"></i>
+                                                        Confirmed by the patient
+                                                    </div>
+                                                @endif
+                                                @if($nextAppt->status === 'REJECTED')
+                                                    <div class="text-danger font-weight-bold font-size-11 mt-1">
+                                                        <i class="fa fa-stop"></i>
+                                                        Rejected by the patient
+                                                    </div>
+                                                @endif
+                                            @endif
+                                        </div>
                                         <a href="#" class="ack-client-pro-change ml-3" data-uid="{{$assoc->uid}}">Stamp</a>
                                     </div>
                                 @endforeach
@@ -220,9 +323,39 @@
                             <div class="mb-3 border rounded px-3 py-2 ack-container">
                                 <p class="pt-1 mb-2"><b>New Patients</b></p>
                                 @foreach($newNAAssociations as $assoc)
-                                    <div class="mb-1">You have been assigned as the Care Coordinator for
-                                        <a href="/patients/view/{{$assoc->patient->uid}}" class="d-inline-block width-150px">{{$assoc->patient->displayName()}}</a>.
-                                        <a href="#" class="ack-client-pro-change ml-3" data-uid="{{$assoc->uid}}">Stamp</a>
+                                    <div class="d-flex align-items-start bg-light mb-2 px-2 py-1">
+                                        <div class="flex-grow-1">
+                                            You are now the Care Coordinator for
+                                            <a href="/patients/view/{{$assoc->patient->uid}}" class="">{{$assoc->patient->displayName()}}</a>
+                                            <?php $nextAppt = $assoc->patient->nextAppointment(); ?>
+                                            @if($nextAppt)
+                                                <div class="font-size-11">
+                                                    <span class="text-secondary font-size-11">Appt.</span>
+                                                    {{$nextAppt->pro->displayName()}}
+                                                    <span class="text-secondary font-size-11">on</span>
+                                                    {{friendlier_date_time($nextAppt->raw_date . ' ' . $nextAppt->raw_start_time)}}
+                                                </div>
+                                                @if($nextAppt->status === 'CREATED')
+                                                    <div class="text-warning-mellow font-weight-bold font-size-11 mt-1">
+                                                        <i class="fa fa-exclamation-triangle"></i>
+                                                        Confirmation pending
+                                                    </div>
+                                                @endif
+                                                @if($nextAppt->status === 'CONFIRMED')
+                                                    <div class="text-success font-weight-bold font-size-11 mt-1">
+                                                        <i class="fa fa-check"></i>
+                                                        Confirmed by the patient
+                                                    </div>
+                                                @endif
+                                                @if($nextAppt->status === 'REJECTED')
+                                                    <div class="text-danger font-weight-bold font-size-11 mt-1">
+                                                        <i class="fa fa-stop"></i>
+                                                        Rejected by the patient
+                                                    </div>
+                                                @endif
+                                            @endif
+                                        </div>
+                                        <a href="#" class="ack-client-pro-change" data-uid="{{$assoc->uid}}">Stamp</a>
                                     </div>
                                 @endforeach
                             </div>
@@ -374,14 +507,31 @@
                                         <a :href="'/patients/view/' + event.clientUid" class="font-weight-bold">@{{ event.clientName }}</a>
                                         <span class="small d-inline-block pl-2 text-secondary font-weight-normal">@{{ event.clientSummary }}</span>
                                     </div>
-                                    <div>
-                                        Status: <b class="text-secondary">@{{ event.status }}</b>
-                                        &nbsp;/&nbsp;
+                                    <div class="d-flex align-items-baseline">
+                                        <div v-if="event.status === 'CREATED'" class="text-warning-mellow font-weight-bold">
+                                            <i class="fa fa-exclamation-triangle"></i>
+                                            Confirmation pending
+                                        </div>
+                                        <div v-else-if="event.status === 'CONFIRMED'" class="text-success font-weight-bold">
+                                            <i class="fa fa-check"></i>
+                                            Confirmed by the patient
+                                        </div>
+                                        <div v-else-if="event.status === 'REJECTED'" class="text-danger font-weight-bold">
+                                            <i class="fa fa-stop"></i>
+                                            Rejected by the patient
+                                        </div>
+                                        <div v-else class="text-secondary">
+                                            Status: <b>@{{ event.status }}</b>
+                                        </div>
+                                        <span class="mx-2 text-secondary">|</span>
                                         <a :href="'/patients/view/' + event.clientUid + '/calendar/' + event.uid">
                                             <i class="fa fa-edit"></i>
                                             Edit Appointment
                                         </a>
                                     </div>
+                                    <div class="mt-1" :class="event.coverage !== 'YES' ? (event.coverage === 'NO' ? 'text-danger' : 'text-warning-mellow') : 'text-success'">
+                                        Coverage Status: <b>@{{ event.coverage }}</b>
+                                    </div>
                                 </div>
                                 <div class="ml-auto">
                                     <select v-model="event.newStatus"
@@ -708,7 +858,7 @@
                     this.loadMeasurements();
                 }
             });
-            // refresh once ticket popup is closed
+            /*// refresh once ticket popup is closed
             $('body').off('stag-popup-closed')
             $('body').on('stag-popup-closed', function() {
                 if($('#pro-dashboard-container').length) {
@@ -717,7 +867,7 @@
                         fastLoad('/?tab=' + activeTab);
                     }
                 }
-            });
+            });*/
             // ticket-popup
             $(document)
                 .off('click', '.ticket-popup-trigger')
@@ -738,7 +888,7 @@
                 .off('click', '.ack-client-pro-change')
                 .on('click', '.ack-client-pro-change', function() {
                     let trigger = $(this).text('…');
-                    $.post('/api/clientProPage/accept', {
+                    $.post('/api/clientProChange/accept', {
                         uid: $(this).attr('data-uid')
                     }, _data => {
                         if(!hasResponseError(_data)) {
@@ -781,6 +931,56 @@
                     }, 'json');
                     return false;
                 });
+
+            $(document)
+                .off('click', '.ack-pro-appt-update')
+                .on('click', '.ack-pro-appt-update', function() {
+                    let trigger = $(this).text('…');
+                    $.post('/api/appointmentConfirmationDecision/acknowledgeAsAppointmentPro', {
+                        uid: $(this).attr('data-uid')
+                    }, _data => {
+                        if(!hasResponseError(_data)) {
+                            trigger.hide();
+                            let doneElem = $('<i class="text-success fa fa-check"></i>');
+                            doneElem.insertAfter(trigger);
+                            setTimeout(() => {
+                                let ackContainer = trigger.closest('tbody');
+                                trigger.closest('tr').slideUp('fast', function() {
+                                    $(this).remove();
+                                    if(!ackContainer.find('>tr').length) {
+                                        ackContainer.remove();
+                                    }
+                                });
+                            }, 500);
+                        }
+                    }, 'json');
+                    return false;
+                });
+
+            $(document)
+                .off('click', '.ack-na-appt-update')
+                .on('click', '.ack-na-appt-update', function() {
+                    let trigger = $(this).text('…');
+                    $.post('/api/appointmentConfirmationDecision/acknowledgeAsClientDefaultNa', {
+                        uid: $(this).attr('data-uid')
+                    }, _data => {
+                        if(!hasResponseError(_data)) {
+                            trigger.hide();
+                            let doneElem = $('<i class="text-success fa fa-check"></i>');
+                            doneElem.insertAfter(trigger);
+                            setTimeout(() => {
+                                let ackContainer = trigger.closest('tbody');
+                                trigger.closest('tr').slideUp('fast', function() {
+                                    $(this).remove();
+                                    if(!ackContainer.find('>tr').length) {
+                                        ackContainer.remove();
+                                    }
+                                });
+                            }, 500);
+                        }
+                    }, 'json');
+                    return false;
+                });
         }
         addMCInitializer('pro-dashboard', init, '#pro-dashboard-container');
     })();

+ 8 - 33
resources/views/app/dashboard/incoming_reports.blade.php

@@ -6,8 +6,9 @@
     <tr>
         <th class="px-2 text-secondary">Created</th>
         <th class="px-2 text-secondary">Patient</th>
+        <th class="px-2 text-secondary">Pro</th>
+        <th class="px-2 text-secondary">Report Date</th>
         <th class="px-2 text-secondary">Report</th>
-        <th class="px-2 text-secondary">Sign</th>
         <th class="px-2 text-secondary">Title</th>
         <th class="px-2 text-secondary">Category</th>
         <th class="px-2 text-secondary">Memo</th>
@@ -27,6 +28,10 @@
                     {{$document->patient->displayName()}}
                 </a>
             </td>
+            <td class="px-2">
+                {{$document->hcp ? $document->hcp->displayName() : '-'}}
+            </td>
+            <td class="px-2">{{ friendly_date_time($document->report_date, false) }}</td>
             <td class="px-2">
                 <div class="d-flex align-items-center">
                     <a class="pdf-viewer-trigger" native target="_blank"
@@ -34,41 +39,11 @@
                        title="View">View</a>
                     @if($document->is_entry_error)
                         <span class="ml-auto text-danger on-hover-opaque" title="Entry Error">
-                                    <i class="fa fa-exclamation-triangle"></i>
-                                </span>
+                            <i class="fa fa-exclamation-triangle"></i>
+                        </span>
                     @endif
                 </div>
             </td>
-            <td class="px-2">
-                @if(!$document->has_hcp_pro_signed)
-                    @if($document->hcp_pro_id === $pro->id)
-                        <div moe relative class="mr-2">
-                            <a start show class="">Sign</a>
-                            <form url="/api/incomingReport/signAsHcp" right>
-                                <input type="hidden" name="uid" value="{{ $document->uid }}">
-                                <p class="small">Are you sure you want to sign this report as HCP?</p>
-                                <div class="d-flex align-items-center">
-                                    <button class="btn btn-sm btn-success mr-2" submit>Sign</button>
-                                    <button class="btn btn-sm btn-default mr-2 border" cancel>Cancel</button>
-                                </div>
-                            </form>
-                        </div>
-                    @else
-                        -
-                    @endif
-                @else
-                    <div class="text-success mb-1">
-                        <i class="fa fa-check"></i>
-                        Signed
-                    </div>
-                    @if($document->hcp)
-                        <div class="text-secondary">
-                            <div class="text-sm font-weight-bold">{{$document->hcp->displayName()}}</div>
-                            <div class="text-sm">{{friendlier_date_time($document->hcp_pro_signed_at)}}</div>
-                        </div>
-                    @endif
-                @endif
-            </td>
             <td class="px-2">{{ $document->title }}</td>
             <td class="px-2">{{ $document->category }}{{ $document->subcategory ? ' / ' . $document->subcategory : '' }}</td>
             <td class="px-2">{{ $document->memo }}</td>

+ 63 - 61
resources/views/app/dashboard/measurements.blade.php

@@ -10,7 +10,6 @@
             <th class="border-0 px-2 text-secondary">Timestamp</th>
             <th class="border-0 px-2 text-secondary">Mins this month</th>
             <th class="border-0 px-2 text-secondary">Stamp</th>
-            <th class="border-0 px-2 text-secondary text-center">Entry</th>
         </tr>
     </thead>
     <tbody>
@@ -43,76 +42,79 @@
                             0
                         @endif
                     </td>
+                    <?php /*
                     <td colspan="px-2">
-                        <span moe large relative>
-                            <a start show class="py-0 mb-3 font-weight-bold">Update status</a>
-                            <form url="/api/measurement/updateStatus" right>
-                                <input type="hidden" name="uid" value="{{$measurement->uid}}">
-                                <select name="status" id="" class="form-control input-sm">
-                                    <option value="">--select--</option>
-                                    <option value="ACK">Ok</option>
-                                    <option value="INVALID_ACK">Invalid</option>
-                                </select>
-                                <div class="d-flex align-items-center mt-2">
-                                    <button class="btn btn-sm btn-success mr-2" submit>Submit</button>
-                                    <button class="btn btn-sm btn-default mr-2 border" cancel>Cancel</button>
-                                </div>
-                            </form>
-                        </span>
-                    </td>
-                    <td colspan="px-2">
-                        <div class="text-center">
-                            <span moe large relative>
-                                <a start show class="py-0 mb-3 font-weight-bold">Add</a>
-                                <form url="/api/careMonthEntry/createForRm" right>
-                                    <p class="mb-2 d-block text-left"><b>Add RM Entry</b></p>
-                                    <input type="hidden" name="careMonthUid" value="{{$measurement->care_month_uid}}">
-                                    <input type="hidden" name="proUid" value="{{$pro->uid}}">
-                                    <input type="hidden" name="effectiveDate" value="{{date('Y-m-d')}}">
-                                    <div class="bg-light border rounded p-2 mb-2">
-                                        <div class="mb-1 d-flex align-items-center">
-                                            <span class="width-50px text-left text-secondary">Type</span>
-                                            <div><b>{{ $measurement->label }} </b></div>
+                        <?php
+                        $stampEndPoint = '';
+                        if ($measurement->mcp_pro_id === $pro->id) {
+                            $stampEndPoint = '/api/measurement/stampAsMcp';
+                        } elseif ($measurement->default_na_pro_id === $pro->id || $measurement->rmm_pro_id === $pro->id || $measurement->rme_pro_id === $pro->id) {
+                            $stampEndPoint = '/api/measurement/stampAsNonHcp';
+                        }
+                        ?>
+                        @if(!empty($stampEndPoint))
+                            <div moe relative>
+                                <a href="#" start show>Stamp</a>
+                                <form url="{{$stampEndPoint}}" right class="width-300px">
+                                    <input type="hidden" name="uid" value="{{$measurement->uid}}">
+                                    <p class="mb-1">Stamp this measurement?</p>
+                                    <div class="mt-2 bg-light border p-2">
+                                        <div class="mb-1 text-secondary">{{ $measurement->label }}</div>
+                                        <div class="font-weight-bold mb-1">
+                                            @if($measurement->label === 'BP')
+                                                {{ round($measurement->sbp_mm_hg, 2) }}/{{ round($measurement->dbp_mm_hg, 2) }} mmHg
+                                                <span class="font-weight-normal d-inline-block pl-2">Pulse:</span>
+                                                {{ $measurement->value_pulse }} {{ $measurement->value_irregular === 0?'Irregular':'' }} {{ $measurement->value_irregular === 1?'Regular':'' }}
+                                            @elseif($measurement->label === 'Wt. (lbs.)')
+                                                {{ round($measurement->numeric_value, 2) }} lbs
+                                            @else
+                                                {{ $measurement->value }}
+                                            @endif
                                         </div>
-                                        <div class="d-flex align-items-center">
-                                            <span class="width-50px text-left text-secondary">Value</span>
-                                            <div>
-                                                @if($measurement->label == 'BP')
-                                                <div>
-                                                    <b>{{ $measurement->sbp_mm_hg }}/{{ $measurement->dbp_mm_hg }} mmHg</b>
-                                                </div>
-                                                @endif
-                                                @if($measurement->label == 'Wt. (lbs.)')
-                                                <div>
-                                                    <b>{{ round(floatval($measurement->numeric_value), 2) }}</b> lbs
-                                                </div>
-                                                @endif
-                                            </div>
+                                        <div class="text-sm">
+                                            <?php $timestampInSec = floor($measurement->ts / 1000); ?>
+                                            {{ friendly_date_time_short_with_tz_from_timestamp($timestampInSec, 'EASTERN') }} EST
                                         </div>
                                     </div>
-                                    <div class="mb-2">
-                                        <div class="row">
-                                            <div class="col-6 d-flex align-items-center">
-                                                <label class="text-secondary text-sm my-0 mr-3 text-nowrap">Time (mins)</label>
-                                                <input type="number" min="0" max="5400" class="form-control form-control-sm w-100 cm-time-value" name="timeInMinutes" value="" placeholder="Time (mins.)" required>
+                                    @if($measurement->mcp_pro_id !== $pro->id)
+                                        <div class="mb-2 border border-info p-2 mt-2 bg-light">
+                                            <span>I have had interactive communication with {{$measurement->name_first}} {{$measurement->name_last}} during this care month.</span>
+                                            <div class="d-flex border-top mt-2">
+                                                <label class="mt-2 mb-0 d-inline-flex align-items-center mr-3">
+                                                    <input type="radio" class="mr-2" name="communicatedToPatient" value="true">
+                                                    <span>Yes</span>
+                                                </label>
+                                                <label class="mt-2 mb-0 d-inline-flex align-items-center">
+                                                    <input type="radio" class="mr-2" name="communicatedToPatient" value="false" checked>
+                                                    <span>No</span>
+                                                </label>
                                             </div>
                                         </div>
-                                    </div>
+                                    @else
+                                        <input type="hidden" name="communicatedToPatient" value="false">
+                                    @endif
                                     <div class="mb-2">
-                                        <div class="row">
-                                            <div class="col-12 text-left">
-                                                <label class="text-secondary text-sm mb-1">Details</label>
-                                                <textarea class="form-control form-control-sm" rows="4" name="contentText">{{ 'Reviewed ' . $measurement->label . ' measurement' }}</textarea>
-                                            </div>
-                                        </div>
+                                        <label class="mb-1 text-secondary text-sm">Memo</label>
+                                        <textarea class="form-control form-control-sm" name="memo"></textarea>
                                     </div>
-                                    <div class="d-flex align-items-center">
-                                        <button class="btn btn-sm btn-success mr-2" submit>Submit</button>
-                                        <button class="btn btn-sm btn-default mr-2 border" cancel>Cancel</button>
+                                    <div class="form-group m-0">
+                                        <button submit class="btn btn-primary btn-sm mr-2">Submit</button>
+                                        <button cancel class="btn btn-default border btn-sm mr-2">Cancel</button>
                                     </div>
                                 </form>
-                            </span>
-                        </div>
+                            </div>
+                        @endif
+                    </td>
+                    */ ?>
+                    <td class="px-2">
+                        <a native target="_blank"
+                           open-in-stag-popup
+                           update-parent
+                           mc-initer="cm-matrix-{{$measurement->client_id}}"
+                           title="Care Month Matrix: {{date('M Y', strtotime($measurement->care_month_start_date))}}"
+                           href="/patient-care-month-matrix/{{$measurement->care_month_uid}}">
+                            View &amp; Stamp
+                        </a>
                     </td>
                 </tr>
             <?php endforeach ?>

+ 12 - 0
resources/views/app/fdb-pg/fdb-allergy-suggest.blade.php

@@ -0,0 +1,12 @@
+@if(!count($matches))
+    <span class="d-block no-suggest-items">No matches!</span>
+@endif
+<?php $activeSet = false; ?>
+@foreach($matches as $match)
+    <a native class="d-block suggest-item fdb-suggest text-nowrap {{ $activeSet ? '' : 'active'  }}" href="#"
+       data-dam-concept-id="{{$match->dam_concept_id}}" data-dam-concept-id-typ="{{$match->dam_concept_id_typ}}">
+        {{$match->dam_concept_id_desc}} <span class="text-sm">({{$match->dam_concept_id_typ == 6 ? 'ingredient' : ($match->dam_concept_id_typ == 1 ? 'allergen group' : 'medication')}})</span>
+    </a>
+    <?php $activeSet = true; ?>
+@endforeach
+

+ 16 - 0
resources/views/app/fdb-pg/fdb-coadministration.blade.php

@@ -0,0 +1,16 @@
+@if(count($coadministration))
+    <div class="d-flex px-2 py-1 bg-white border-bottom align-items-baseline">
+        <span>Count: <b>{{count($coadministration)}}</b></span>
+        <a href="#" class="text-sm ml-auto" onclick="$(this).parent().next('table').toggle(); return false;">Toggle</a>
+    </div>
+    <table class="table table-sm table-striped table-bordered" style="display: none">
+        <tbody>
+        @foreach($coadministration as $item)
+            <tr>
+                <td>{{$item->coadmin_dosing_text}}</td>
+            </tr>
+        @endforeach
+        </tbody>
+    </table>
+@endif
+

+ 25 - 0
resources/views/app/fdb-pg/fdb-contraindications.blade.php

@@ -0,0 +1,25 @@
+@if(!count($contraindications))
+    <span class="d-block no-suggest-items">No contraindications!</span>
+@else
+    <div class="d-flex px-2 py-1 bg-white border-bottom align-items-baseline">
+        <span>Count: <b>{{count($contraindications)}}</b></span>
+        <a href="#" class="text-sm ml-auto" onclick="$(this).parent().next('table').toggle(); return false;">Toggle</a>
+    </div>
+    <table class="table table-sm table-striped table-bordered" style="display: none">
+        <thead>
+        <tr>
+            <th>Severity</th>
+            <th>Contraindication</th>
+        </tr>
+        </thead>
+        <tbody>
+        @foreach($contraindications as $contraindication)
+            <tr>
+                <td class="font-weight-bold">{{$contraindication->ddxcn_sl == 1 ? 'Contraindication' : ($contraindication->ddxcn_sl == 2 ? 'Severe Warning' : 'Moderate Warning')}}</td>
+                <td>{{$contraindication->dxid_desc56}}</td>
+            </tr>
+        @endforeach
+        </tbody>
+    </table>
+@endif
+

+ 12 - 0
resources/views/app/fdb-pg/fdb-dx-suggest.blade.php

@@ -0,0 +1,12 @@
+@if(!count($matches))
+    <span class="d-block no-suggest-items">No matches!</span>
+@endif
+<?php $activeSet = false; ?>
+@foreach($matches as $match)
+    <a native class="d-block suggest-item fdb-suggest text-nowrap {{ $activeSet ? '' : 'active'  }}" href="#"
+       data-dx-id="{{$match->dxid}}">
+        {{$match->dxid_desc56}}
+    </a>
+    <?php $activeSet = true; ?>
+@endforeach
+

+ 27 - 0
resources/views/app/fdb-pg/fdb-geriatric-precautions.blade.php

@@ -0,0 +1,27 @@
+@if(!count($precautions))
+    <span class="d-block no-suggest-items">No geriatric precautions!</span>
+@else
+    <div class="d-flex px-2 py-1 bg-white border-bottom align-items-baseline">
+        <span>Count: <b>{{count($precautions)}}</b></span>
+        <a href="#" class="text-sm ml-auto" onclick="$(this).parent().next('table').toggle(); return false;">Toggle</a>
+    </div>
+    <table class="table table-sm table-striped table-bordered" style="display: none">
+        <thead>
+        <tr>
+            <th>Desc</th>
+            <th>Severity</th>
+            <th>Narrative</th>
+        </tr>
+        </thead>
+        <tbody>
+        @foreach($precautions as $precaution)
+            <tr>
+                <td>{{$precaution->geri_desc}}</td>
+                <td>{{$precaution->geri_sl == 1 ? 'Contraindication' : 'Management or Monitoring Precaution'}}</td>
+                <td>{{$precaution->geri_narrative}}</td>
+            </tr>
+        @endforeach
+        </tbody>
+    </table>
+@endif
+

+ 25 - 0
resources/views/app/fdb-pg/fdb-indications.blade.php

@@ -0,0 +1,25 @@
+@if(!count($indications))
+    <span class="d-block no-suggest-items">No indications!</span>
+@else
+    <div class="d-flex px-2 py-1 bg-white border-bottom align-items-baseline">
+        <span>Count: <b>{{count($indications)}}</b></span>
+        <a href="#" class="text-sm ml-auto" onclick="$(this).parent().next('table').toggle(); return false;">Toggle</a>
+    </div>
+    <table class="table table-sm table-striped table-bordered" style="display: none">
+        <thead>
+        <tr>
+            <th>Indication</th>
+            <th>FDA Approved</th>
+        </tr>
+        </thead>
+        <tbody>
+        @foreach($indications as $indication)
+            <tr>
+                <td class="font-weight-bold">{{$indication->dxid_desc56}}</td>
+                <td>{{$indication->indcts_lbl}}</td>
+            </tr>
+        @endforeach
+        </tbody>
+    </table>
+@endif
+

+ 12 - 0
resources/views/app/fdb-pg/fdb-med-suggest.blade.php

@@ -0,0 +1,12 @@
+@if(!count($matches))
+    <span class="d-block no-suggest-items">No matches!</span>
+@endif
+<?php $activeSet = false; ?>
+@foreach($matches as $match)
+    <a native class="d-block suggest-item fdb-suggest text-nowrap {{ $activeSet ? '' : 'active'  }}" href="#"
+       data-med-name-id="{{$match->med_name_id}}">
+        {{$match->med_name}}
+    </a>
+    <?php $activeSet = true; ?>
+@endforeach
+

+ 667 - 0
resources/views/app/fdb-pg/fdb-rx.blade.php

@@ -0,0 +1,667 @@
+@extends ('layouts/template')
+
+@section('content')
+
+    <style>
+      .fdb-suggestions-container .suggestions-outer {
+        right: auto;
+        left: 0;
+      }
+    </style>
+
+    <div class="p-0 mcp-theme-1" id="fdb-pg">
+        <div class="px-3 py-2 bg-light border-bottom d-flex align-items-center font-weight-bold font-size-14">FDB Playground</div>
+        <div class="p-3 bg-light">
+            <div class="row mb-3">
+                <div class="col-6">
+                    <div class="bg-white p-3 border">
+                        <div class="d-flex align-items-baseline mb-2">
+                            <span class="font-size-14 font-weight-bold">Allergies</span>
+                            <a href="#" v-on:click.prevent="addAllergy()" class="ml-3">+ Add</a>
+                        </div>
+                        <table class="table table-sm table-striped table-bordered m-0">
+                        <thead>
+                        <tr>
+                            <th class="border-bottom-0 text-secondary">Allergy</th>
+                            <th class="border-bottom-0 width-100px"></th>
+                        </tr>
+                        </thead>
+                        <tbody>
+                        <tr v-for="(item, index) in allergies">
+                            <td class="p-0 position-relative">
+                                <input type="text" class="rounded-0 border-0 form-control form-control-sm min-width-unset"
+                                       fdb-allergy-suggest-search :fdb-suggest-group="index">
+                            </td>
+                            <td class="text-center">
+                                <a href="#" v-on:click.prevent="allergies.splice(index, 1); showDrugAllergyNotes();"><i class="fa fa-trash-alt text-danger"></i></a>
+                            </td>
+                        </tr>
+                        </tbody>
+                    </table>
+                    </div>
+                </div>
+                <div class="col-6 pl-0">
+                    <div class="bg-white p-3 border">
+                        <div class="d-flex align-items-baseline mb-2">
+                            <span class="font-size-14 font-weight-bold">Current Problems</span>
+                            <a href="#" v-on:click.prevent="addDx()" class="ml-3">+ Add</a>
+                        </div>
+                        <table class="table table-sm table-striped table-bordered m-0">
+                        <thead>
+                        <tr>
+                            <th class="border-bottom-0 text-secondary">Problem</th>
+                            <th class="border-bottom-0 width-100px"></th>
+                        </tr>
+                        </thead>
+                        <tbody>
+                        <tr v-for="(item, index) in dx">
+                            <td class="p-0 position-relative">
+                                <input type="text" class="rounded-0 border-0 form-control form-control-sm min-width-unset"
+                                       fdb-dx-suggest-search :fdb-suggest-group="index">
+                            </td>
+                            <td class="text-center">
+                                <a href="#" v-on:click.prevent="dx.splice(index, 1)"><i class="fa fa-trash-alt text-danger"></i></a>
+                            </td>
+                        </tr>
+                        </tbody>
+                    </table>
+                    </div>
+                </div>
+            </div>
+            <div class="bg-white p-3 mb-3 border">
+                <div class="d-flex align-items-baseline mb-2">
+                    <span class="font-size-14 font-weight-bold">Medications</span>
+                    <a href="#" v-on:click.prevent="addRx()" class="ml-3">+ Add</a>
+                </div>
+                <table class="table table-sm table-bordered m-0" style="table-layout: fixed">
+                <thead>
+                <tr>
+                    <th class="border-bottom-0 text-secondary">Medication</th>
+                    <th class="border-bottom-0 text-secondary">Route</th>
+                    <th class="border-bottom-0 text-secondary">Dosage</th>
+                    <th class="border-bottom-0 text-secondary">Strength</th>
+                    <th class="border-bottom-0 text-secondary">Side Effects</th>
+                    <th class="border-bottom-0 text-secondary">Ger. Precautions</th>
+                    <th class="border-bottom-0 text-secondary">Indications</th>
+                    <th class="border-bottom-0 text-secondary">Contraindications</th>
+                    <th class="border-bottom-0 width-100px"></th>
+                </tr>
+                </thead>
+                <tbody>
+                <tr v-for="(item, index) in rx">
+                    <td class="p-0 position-relative">
+                        <input type="text" class="rounded-0 border-0 form-control form-control-sm min-width-unset"
+                               fdb-med-suggest-search :fdb-suggest-group="index">
+                    </td>
+                    <td class="p-0 position-relative">
+                        <select class="rounded-0 border-0 form-control form-control-sm min-width-unset"
+                                fdb-med-suggest-route :fdb-suggest-group="index" v-model="item.routed_med_id"
+                                disabled>
+                        </select>
+                    </td>
+                    <td class="p-0 position-relative">
+                        <select class="rounded-0 border-0 form-control form-control-sm min-width-unset"
+                                fdb-med-suggest-dosage :fdb-suggest-group="index" v-model="item.routed_dosage_form_med_id"
+                                disabled>
+                        </select>
+                    </td>
+                    <td class="p-0 position-relative">
+                        <select class="rounded-0 border-0 form-control form-control-sm min-width-unset"
+                                fdb-med-suggest-strength :fdb-suggest-group="index" v-model="item.gcn_seqno"
+                                disabled>
+                        </select>
+                    </td>
+
+                    <td class="p-0 overflow-auto side-effects" :fdb-suggest-group="index">
+
+                    </td>
+                    <td class="p-0 overflow-auto geriatric-precautions" :fdb-suggest-group="index">
+
+                    </td>
+                    <td class="p-0 overflow-auto indications" :fdb-suggest-group="index">
+
+                    </td>
+                    <td class="p-0 overflow-auto contraindications" :fdb-suggest-group="index">
+
+                    </td>
+                    <td class="text-center">
+                        <a href="#" v-on:click.prevent="rx.splice(index, 1); showDrugAllergyNotes(); showDrugCoadministrationNotes(); showDuplicateTherapyNotes()"><i class="fa fa-trash-alt text-danger"></i></a>
+                    </td>
+                </tr>
+                </tbody>
+            </table>
+            </div>
+            <div class="row">
+                <div class="col-3">
+                    <div class="bg-white p-3 border">
+                        <div class="d-flex align-items-baseline mb-2">
+                            <span class="font-size-14 font-weight-bold">Drug Allergy Notes</span>
+                        </div>
+                        <div class="drug-allergies"></div>
+                    </div>
+                </div>
+                <div class="col-3 pl-0">
+                    <div class="bg-white p-3 border">
+                        <div class="d-flex align-items-baseline mb-2">
+                            <span class="font-size-14 font-weight-bold">Drug Drug Interaction Notes</span>
+                        </div>
+                        <div class="drug-drug-interaction"></div>
+                    </div>
+                </div>
+                <div class="col-3 pl-0">
+                    <div class="bg-white p-3 border">
+                        <div class="d-flex align-items-baseline mb-2">
+                            <span class="font-size-14 font-weight-bold">Duplicate Therapy Notes</span>
+                        </div>
+                        <div class="duplicate-therapy"></div>
+                    </div>
+                </div>
+                <div class="col-3 pl-0">
+                    <div class="bg-white p-3 border">
+                        <div class="d-flex align-items-baseline mb-2">
+                            <span class="font-size-14 font-weight-bold">Coadministration Notes</span>
+                        </div>
+                        <div class="drug-coadministration"></div>
+                    </div>
+                </div>
+            </div>
+        </div>
+    </div>
+
+    <script>
+        (function() {
+
+            let suggestionsOuter = null;
+
+            const debounce = (func, wait) => {
+                let timeout;
+                return function executedFunction(...args) {
+                    const later = () => {
+                        clearTimeout(timeout);
+                        func(...args);
+                    };
+                    clearTimeout(timeout);
+                    timeout = setTimeout(later, wait);
+                };
+            };
+
+            var lastTerm = '';
+            var returnedFunction = debounce(function (elem) {
+                let term = elem.val();
+                if (!!term && lastTerm !== term) {
+                    let ep = false;
+                    if($(elem).is('[fdb-med-suggest-search]')) {
+                        ep = '/fdb-med-suggest';
+                    }
+                    else if($(elem).is('[fdb-dx-suggest-search]')) {
+                        ep = '/fdb-dx-suggest';
+                    }
+                    else if($(elem).is('[fdb-allergy-suggest-search]')) {
+                        ep = '/fdb-allergy-suggest';
+                    }
+                    $.get(ep + '?term=' + $.trim(term), function (_data) {
+                        suggestionsOuter.html(_data).removeClass('d-none');
+                    });
+                    lastTerm = term;
+                } else {
+                    suggestionsOuter.addClass('d-none');
+                }
+            }, 250);
+
+            function handleKeydown(elem, e) {
+                let term = $.trim(elem.val());
+                let activeItem = suggestionsOuter.find('.suggest-item.active');
+                switch (e.which) {
+                    case 27:
+                        suggestionsOuter.addClass('d-none');
+                        return false;
+                    case 38:
+                        if (activeItem.prev().length) {
+                            activeItem.prev()
+                                .addClass('active')
+                                .siblings().removeClass('active');
+                            activeItem = suggestionsOuter.find('.suggest-item.active');
+                            if (activeItem.length) {
+                                activeItem[0].scrollIntoView();
+                            }
+                        }
+                        return false;
+                    case 40:
+                        if (activeItem.next().length) {
+                            activeItem.next()
+                                .addClass('active')
+                                .siblings().removeClass('active');
+                            activeItem = suggestionsOuter.find('.suggest-item.active');
+                            if (activeItem.length) {
+                                activeItem[0].scrollIntoView();
+                            }
+                        }
+                        return false;
+                    case 13:
+                        if (activeItem.length) {
+                            activeItem.first().click();
+                        }
+                        return false;
+                    default:
+                        if (!!term) {
+                            suggestionsOuter
+                                .html('<span class="d-block no-suggest-items">Searching...</span>')
+                                .removeClass('d-none');
+                            returnedFunction(elem);
+                        } else {
+                            suggestionsOuter.addClass('d-none');
+                        }
+                        break;
+                }
+            }
+
+            function handleKeypress(elem, e) {
+                var term = $.trim(elem.val());
+                if (!!term) {
+                    suggestionsOuter
+                        .html('<span class="d-block no-suggest-items">Searching...</span>')
+                        .removeClass('d-none');
+                    returnedFunction(elem);
+                } else {
+                    suggestionsOuter.addClass('d-none');
+                }
+            }
+
+            function fillSideEffects(_group, _gcn_seqno) {
+                let container = $('.side-effects[fdb-suggest-group=' + _group + ']');
+                container.empty();
+                $.get('/fdb-side-effects?gcn-seq-no=' + _gcn_seqno, _data => {
+                    container.html(_data);
+                });
+            }
+
+            function fillGeriatricPrecautions(_group, _gcn_seqno) {
+                let container = $('.geriatric-precautions[fdb-suggest-group=' + _group + ']');
+                container.empty();
+                $.get('/fdb-geriatric-precautions?gcn-seq-no=' + _gcn_seqno, _data => {
+                    container.html(_data);
+                });
+            }
+
+            function fillIndications(_group, _gcn_seqno) {
+                let container = $('.indications[fdb-suggest-group=' + _group + ']');
+                container.empty();
+                $.get('/fdb-indications?gcn-seq-no=' + _gcn_seqno, _data => {
+                    container.html(_data);
+                });
+            }
+
+            function fillContraindications(_group, _gcn_seqno) {
+                let container = $('.contraindications[fdb-suggest-group=' + _group + ']');
+                container.empty();
+                $.get('/fdb-contraindications?routed-med-id=' + _gcn_seqno, _data => {
+                    container.html(_data);
+                });
+            }
+
+            addMCInitializer('fdb-pg', function() {
+
+                window.fdbPGApp = new Vue({
+                    el: '#fdb-pg',
+                    delimiters: ['@{{', '}}'],
+                    data: {
+                        allergies: [{
+
+                        }],
+                        dx: [{
+
+                        }],
+                        rx: [{
+
+                        }],
+                    },
+                    methods: {
+                        addRx: function() {
+                            this.rx.push({});
+                            Vue.nextTick(() => {
+                                this.initFDBRxSuggest();
+                                $('[fdb-med-suggest-search]').last().focus();
+                            });
+                        },
+                        addDx: function() {
+                            this.dx.push({});
+                            Vue.nextTick(() => {
+                                this.initFDBDxSuggest();
+                                $('[fdb-dx-suggest-search]').last().focus();
+                            });
+                        },
+                        addAllergy: function() {
+                            this.allergies.push({});
+                            Vue.nextTick(() => {
+                                this.initFDBAllergySuggest();
+                                $('[fdb-allergy-suggest-search]').last().focus();
+                            });
+                        },
+                        showDrugAllergyNotes: function() {
+                            $('.drug-allergies').html('');
+                            if(this.allergies && this.allergies.length && this.rx && this.rx.length) {
+                                $.get('/fdb-drug-allergies', {
+                                    data: JSON.stringify({
+                                        allergies: this.allergies,
+                                        rx: this.rx
+                                    })
+                                }, _data => {
+                                    $('.drug-allergies').html(_data);
+                                });
+                            }
+                        },
+                        showDrugDrugInteractionNotes: function() {
+                            $('.drug-drug-interaction').html('');
+                            if(this.rx && this.rx.length > 1) {
+                                $.get('/fdb-drug-drug-interaction', {
+                                    data: JSON.stringify({
+                                        rx: this.rx
+                                    })
+                                }, _data => {
+                                    $('.drug-drug-interaction').html(_data);
+                                });
+                            }
+                        },
+                        showDrugCoadministrationNotes: function() {
+                            $('.drug-coadministration').html('');
+                            if(this.rx && this.rx.length > 1) {
+                                let gcnSeqNos = [];
+                                for (let i = 0; i < this.rx.length; i++) {
+                                    gcnSeqNos.push(this.rx[i].gcn_seqno);
+                                }
+                                gcnSeqNos = gcnSeqNos.join(",");
+                                $.get('/fdb-drug-coadministration', {
+                                    'gcn-seqnos': gcnSeqNos
+                                }, _data => {
+                                    $('.drug-coadministration').html(_data);
+                                });
+                            }
+                        },
+                        showDuplicateTherapyNotes: function() {
+                            $('.duplicate-therapy').html('');
+                            if(this.rx && this.rx.length > 1) {
+                                $.get('/fdb-duplicate-therapy', {
+                                    data: JSON.stringify({
+                                        rx: this.rx
+                                    })
+                                }, _data => {
+                                    $('.duplicate-therapy').html(_data);
+                                });
+                            }
+                        },
+                        initFDBRxSuggest: function() {
+                            $('[fdb-med-suggest-search]:not([fdb-suggest-initialized])').each(function() {
+                                let elem = $(this);
+                                elem.next('.fdb-suggestions-container').remove();
+                                $('<div class="fdb-suggestions-container position-relative" fdb-suggest-group="' + elem.attr('fdb-suggest-group') + '">' +
+                                    '<div class="suggestions-outer fdb-suggestions position-absolute d-none"></div>' +
+                                    '</div>').insertAfter(elem);
+
+                                elem
+                                    .off('keydown.fdb-suggest')
+                                    .on('keydown.fdb-suggest', function (e) {
+                                        suggestionsOuter = $(this).next('.fdb-suggestions-container').find('>.suggestions-outer');
+                                        return handleKeydown($(this), e);
+                                    })
+                                    .off('keypress.fdb-suggest')
+                                    .on('keypress.fdb-suggest', function (e) {
+                                        suggestionsOuter = $(this).next('.fdb-suggestions-container').find('>.suggestions-outer');
+                                        return handleKeypress($(this), e);
+                                    });
+
+                                $(this).attr('fdb-suggest-initialized', 1);
+                            });
+                        },
+                        initFDBDxSuggest: function() {
+                            $('[fdb-dx-suggest-search]:not([fdb-suggest-initialized])').each(function() {
+                                let elem = $(this);
+                                elem.next('.fdb-suggestions-container').remove();
+                                $('<div class="fdb-suggestions-container position-relative" fdb-suggest-group="' + elem.attr('fdb-suggest-group') + '">' +
+                                    '<div class="suggestions-outer fdb-suggestions position-absolute d-none"></div>' +
+                                    '</div>').insertAfter(elem);
+
+                                elem
+                                    .off('keydown.fdb-suggest')
+                                    .on('keydown.fdb-suggest', function (e) {
+                                        suggestionsOuter = $(this).next('.fdb-suggestions-container').find('>.suggestions-outer');
+                                        return handleKeydown($(this), e);
+                                    })
+                                    .off('keypress.fdb-suggest')
+                                    .on('keypress.fdb-suggest', function (e) {
+                                        suggestionsOuter = $(this).next('.fdb-suggestions-container').find('>.suggestions-outer');
+                                        return handleKeypress($(this), e);
+                                    });
+
+                                $(this).attr('fdb-suggest-initialized', 1);
+                            });
+                        },
+                        initFDBAllergySuggest: function() {
+                            $('[fdb-allergy-suggest-search]:not([fdb-suggest-initialized])').each(function() {
+                                let elem = $(this);
+                                elem.next('.fdb-suggestions-container').remove();
+                                $('<div class="fdb-suggestions-container position-relative" fdb-suggest-group="' + elem.attr('fdb-suggest-group') + '">' +
+                                    '<div class="suggestions-outer fdb-suggestions position-absolute d-none"></div>' +
+                                    '</div>').insertAfter(elem);
+
+                                elem
+                                    .off('keydown.fdb-suggest')
+                                    .on('keydown.fdb-suggest', function (e) {
+                                        suggestionsOuter = $(this).next('.fdb-suggestions-container').find('>.suggestions-outer');
+                                        return handleKeydown($(this), e);
+                                    })
+                                    .off('keypress.fdb-suggest')
+                                    .on('keypress.fdb-suggest', function (e) {
+                                        suggestionsOuter = $(this).next('.fdb-suggestions-container').find('>.suggestions-outer');
+                                        return handleKeypress($(this), e);
+                                    });
+
+                                $(this).attr('fdb-suggest-initialized', 1);
+                            });
+                        }
+                    },
+                    mounted: function() {
+
+                        let vueApp = this;
+
+                        // on auto-suggest med selection
+                        $(document).off('click', '.suggest-item.fdb-suggest[data-med-name-id]');
+                        $(document).on('click', '.suggest-item.fdb-suggest[data-med-name-id]', function () {
+
+                            $('.suggestions-outer.fdb-suggestions').addClass('d-none');
+
+                            let medNameID = $(this).attr('data-med-name-id'),
+                                label = $.trim($(this).text()),
+                                group = $(this).closest('.fdb-suggestions-container').attr('fdb-suggest-group');
+
+                            // set value
+                            let input = $(this).closest('.position-relative').prev('[fdb-med-suggest-search]');
+                            input.val(label);
+                            input.attr('data-med-name-id', medNameID);
+                            input.trigger('input');
+                            input.trigger('change');
+
+                            // vue value
+                            vueApp.rx[group].rx = label;
+                            vueApp.rx[group].med_name_id = medNameID;
+
+                            $(document).trigger('fdb-med-changed', [group]);
+
+                            return false;
+                        });
+
+                        // on auto-suggest dx selection
+                        $(document).off('click', '.suggest-item.fdb-suggest[data-dx-id]');
+                        $(document).on('click', '.suggest-item.fdb-suggest[data-dx-id]', function () {
+
+                            $('.suggestions-outer.fdb-suggestions').addClass('d-none');
+
+                            let dxID = $(this).attr('data-dx-id'),
+                                label = $.trim($(this).text()),
+                                group = $(this).closest('.fdb-suggestions-container').attr('fdb-suggest-group');
+
+                            // set value
+                            let input = $(this).closest('.position-relative').prev('[fdb-dx-suggest-search]');
+                            input.val(label);
+                            input.attr('data-dx-id', dxID);
+                            input.trigger('input');
+                            input.trigger('change');
+
+                            // vue value
+                            vueApp.dx[group].problem = label;
+                            vueApp.dx[group].dxid = dxID;
+
+                            $(document).trigger('fdb-dx-changed', [group]);
+
+                            return false;
+                        });
+
+                        // on auto-suggest allergy selection
+                        $(document).off('click', '.suggest-item.fdb-suggest[data-dam-concept-id]');
+                        $(document).on('click', '.suggest-item.fdb-suggest[data-dam-concept-id]', function () {
+
+                            $('.suggestions-outer.fdb-suggestions').addClass('d-none');
+
+                            let damConceptID = $(this).attr('data-dam-concept-id'),
+                                damConceptIDTyp = $(this).attr('data-dam-concept-id-typ'),
+                                label = $.trim($(this).text()),
+                                group = $(this).closest('.fdb-suggestions-container').attr('fdb-suggest-group');
+
+                            // set value
+                            let input = $(this).closest('.position-relative').prev('[fdb-allergy-suggest-search]');
+                            input.val(label);
+                            input.attr('data-dam-concept-id', damConceptID);
+                            input.attr('data-dam-concept-id-type', damConceptIDTyp);
+                            input.trigger('input');
+                            input.trigger('change');
+
+                            // vue value
+                            vueApp.allergies[group].allergen = label;
+                            vueApp.allergies[group].dam_concept_id = damConceptID;
+                            vueApp.allergies[group].dam_concept_id_typ = damConceptIDTyp;
+
+                            $(document).trigger('fdb-allergy-changed', [group]);
+
+                            vueApp.showDrugAllergyNotes();
+
+                            return false;
+                        });
+
+                        // med changed, update routes
+                        $(document).off('fdb-med-changed');
+                        $(document).on('fdb-med-changed', function(e, group) {
+
+                            // clear vue values
+                            vueApp.rx[group].routed_med_id = null;
+                            vueApp.rx[group].routed_dosage_form_med_id = null;
+                            vueApp.rx[group].medid = null;
+                            vueApp.rx[group].gcn_seqno = null;
+
+                            let routeSelect = $('[fdb-med-suggest-route][fdb-suggest-group='+group+']').empty().prop('disabled', true);
+                            let dosageSelect = $('[fdb-med-suggest-dosage][fdb-suggest-group='+group+']').empty().prop('disabled', true);
+                            let strengthSelect = $('[fdb-med-suggest-strength][fdb-suggest-group='+group+']').empty().prop('disabled', true);
+                            let medNameID = $('[fdb-med-suggest-search][fdb-suggest-group='+group+']').attr('data-med-name-id');
+                            $.get('/fdb-routed-meds?med-name-id=' + medNameID, _data => {
+                                routeSelect
+                                    .empty()
+                                    .append('<option value="">-- select --</option>');
+                                for (let i = 0; i < _data.length; i++) {
+                                    routeSelect.append('<option value="' + _data[i].routed_med_id + '">' + _data[i].med_routed_med_id_desc + '</option>')
+                                }
+                                routeSelect.prop('disabled', false);
+                                if(_data.length === 1) {
+                                    vueApp.rx[group].routed_med_id = _data[0].routed_med_id;
+                                    routeSelect.val(_data[0].routed_med_id).trigger('change');
+                                }
+                            }, 'json');
+                            routeSelect.prop('disabled', false);
+                        });
+
+                        // on route selection
+                        $(document).off('change', '[fdb-med-suggest-route]');
+                        $(document).on('change', '[fdb-med-suggest-route]', function () {
+                            let group = $(this).attr('fdb-suggest-group');
+
+                            // clear vue values
+                            vueApp.rx[group].routed_dosage_form_med_id = null;
+                            vueApp.rx[group].medid = null;
+                            vueApp.rx[group].gcn_seqno = null;
+
+                            let dosageSelect = $('[fdb-med-suggest-dosage][fdb-suggest-group='+group+']').empty().prop('disabled', true);
+                            let strengthSelect = $('[fdb-med-suggest-strength][fdb-suggest-group='+group+']').empty().prop('disabled', true);
+                            let routedMedID = $('[fdb-med-suggest-route][fdb-suggest-group='+$(this).attr('fdb-suggest-group')+']').val();
+                            $.get('/fdb-routed-dosages?routed-med-id=' + routedMedID, _data => {
+                                dosageSelect
+                                    .empty()
+                                    .append('<option value="">-- select --</option>');
+                                for (let i = 0; i < _data.length; i++) {
+                                    dosageSelect.append('<option value="' + _data[i].routed_dosage_form_med_id + '">' + _data[i].med_routed_df_med_id_desc + '</option>')
+                                }
+                                dosageSelect.prop('disabled', false);
+                                if(_data.length === 1) {
+                                    vueApp.rx[group].routed_dosage_form_med_id = _data[0].routed_dosage_form_med_id;
+                                    dosageSelect.val(_data[0].routed_dosage_form_med_id).trigger('change');
+                                }
+                            }, 'json');
+                        });
+
+                        // on dosage selection
+                        $(document).off('change', '[fdb-med-suggest-dosage]');
+                        $(document).on('change', '[fdb-med-suggest-dosage]', function () {
+                            let group = $(this).attr('fdb-suggest-group');
+
+                            vueApp.rx[group].medid = null;
+                            vueApp.rx[group].gcn_seqno = null;
+
+                            let strengthSelect = $('[fdb-med-suggest-strength][fdb-suggest-group='+group+']').empty().prop('disabled', true);
+                            let dosageFormMedID = $('[fdb-med-suggest-dosage][fdb-suggest-group='+$(this).attr('fdb-suggest-group')+']').val();
+                            $.get('/fdb-meds?dosage-form-med-id=' + dosageFormMedID, _data => {
+                                strengthSelect
+                                    .empty()
+                                    .append('<option value="">-- select --</option>');
+                                for (let i = 0; i < _data.length; i++) {
+                                    strengthSelect.append('<option data-medid="' + _data[i].medid + '" value="' + _data[i].gcn_seqno + '">' + _data[i].med_medid_desc + '</option>')
+                                }
+                                strengthSelect.prop('disabled', false);
+                                if(_data.length === 1) {
+                                    vueApp.rx[group].medid = _data[0].medid;
+                                    vueApp.rx[group].gcn_seqno = _data[0].gcn_seqno;
+                                    strengthSelect.val(_data[0].gcn_seqno).trigger('change');
+                                }
+                            }, 'json');
+                        });
+
+                        // on strength (medid) selection
+                        $(document).off('change', '[fdb-med-suggest-strength]');
+                        $(document).on('change', '[fdb-med-suggest-strength]', function () {
+
+                            let group = $(this).attr('fdb-suggest-group');
+                            vueApp.rx[group].medid = $(this).find('option:selected').attr('data-medid');
+
+                            fillSideEffects($(this).attr('fdb-suggest-group'), $(this).val());
+                            fillGeriatricPrecautions($(this).attr('fdb-suggest-group'), $(this).val());
+                            fillIndications($(this).attr('fdb-suggest-group'), $(this).val());
+
+                            let routedMedID = $('[fdb-med-suggest-route][fdb-suggest-group='+$(this).attr('fdb-suggest-group')+']').val();
+                            fillContraindications($(this).attr('fdb-suggest-group'), routedMedID);
+
+                            vueApp.showDrugAllergyNotes();
+                            vueApp.showDrugDrugInteractionNotes();
+                            vueApp.showDuplicateTherapyNotes();
+                            vueApp.showDrugCoadministrationNotes();
+                        });
+
+                        Vue.nextTick(() => {
+                            this.initFDBAllergySuggest();
+                            this.initFDBDxSuggest();
+                            this.initFDBRxSuggest();
+                            $('[fdb-allergy-suggest-search]').first().focus();
+                        });
+
+                    }
+                })
+
+            }, '#fdb-pg');
+        }).call(window);
+    </script>
+
+@endsection

+ 27 - 0
resources/views/app/fdb-pg/fdb-side-effects.blade.php

@@ -0,0 +1,27 @@
+@if(!count($sides))
+    <span class="d-block no-suggest-items">No side effects!</span>
+@else
+    <div class="d-flex px-2 py-1 bg-white border-bottom align-items-baseline">
+        <span>Count: <b>{{count($sides)}}</b></span>
+        <a href="#" class="text-sm ml-auto" onclick="$(this).parent().next('table').toggle(); return false;">Toggle</a>
+    </div>
+    <table class="table table-sm table-striped table-bordered" style="display: none">
+        <thead>
+        <tr>
+            <th>Side Effect</th>
+            <th>Severity</th>
+            <th>Frequency</th>
+        </tr>
+        </thead>
+        <tbody>
+        @foreach($sides as $side)
+            <tr>
+                <td class="font-weight-bold">{{$side->dxid_desc56}}</td>
+                <td>{{$side->side_sev == 0 ? 'Not Severe' : 'Severe'}}</td>
+                <td>{{$side->side_sev == 0 ? 'High' : ($side->side_sev == 1 ? 'Low' : 'Rare')}}</td>
+            </tr>
+        @endforeach
+        </tbody>
+    </table>
+@endif
+

+ 17 - 6
resources/views/app/generic-bills/add-bill-form/Note.blade.php

@@ -29,33 +29,44 @@
 
 <form url="/api/bill/createForGeneric">
     @if(hasActiveGenericBill($genericPro, @$patient, @$entityType, @$entityUid))
-        <div class="border rounded bg-aliceblue p-2 width-200px">
-            <i class="fa fa-exclamation-triangle text-warning-mellow mr-1"></i>
-            An uncancelled NA bill already exists for this note!
+        <div class="border rounded bg-aliceblue p-2 width-200px d-flex align-items-baseline">
+            <i class="fa fa-exclamation-triangle text-warning-mellow mr-2"></i>
+            <span>An uncancelled NA bill already exists for this note!</span>
+        </div>
+    @elseif($note && !$note->hasTreatmentServicesBillByHCP())
+        <div class="border rounded bg-aliceblue p-2 width-200px d-flex align-items-baseline">
+            <i class="fa fa-exclamation-triangle text-warning-mellow mr-2"></i>
+            <span>Pending HCP Signing of Treatment Services</span>
         </div>
     @else
         @include('app.generic-bills.add-bill-form._default-fields')
         <div class="mb-2 border px-2 pt-2 generic-bill-actions">
             <p class="text-sm mb-1 text-secondary font-weight-bold">Please indicate the activities time was spent on:</p>
             <input type="text" name="genericDescription" value="" class="zero-height-field m-0 p-0 border-0" required>
-            <label class="d-flex align-items-center">
+            <label class="d-flex align-items-baseline">
                 <input type="checkbox" class="mr-2 my-0 generic-bill-action"
                        data-action="Note reviewed."
                        onchange="return updateGenericBillAction(this)">
                 <span>Note reviewed.</span>
             </label>
-            <label class="d-flex align-items-center">
+            <label class="d-flex align-items-baseline">
                 <input type="checkbox" class="mr-2 my-0 generic-bill-action"
                        data-action="Care coordinated."
                        onchange="return updateGenericBillAction(this)">
                 <span>Care coordinated.</span>
             </label>
-            <label class="d-flex align-items-center">
+            <label class="d-flex align-items-baseline">
                 <input type="checkbox" class="mr-2 my-0 generic-bill-action"
                        data-action="Admin. support for follow-up."
                        onchange="return updateGenericBillAction(this)">
                 <span>Admin. support for follow-up.</span>
             </label>
+            <label class="d-flex align-items-baseline">
+                <input type="checkbox" class="mr-2 my-0 generic-bill-action"
+                       data-action="Provided Patient w/ Visit-Related Education."
+                       onchange="return updateGenericBillAction(this)">
+                <span>Provided Patient w/ Visit-Related Education.</span>
+            </label>
         </div>
         @include('app.generic-bills.add-bill-form._default-actions')
     @endif

+ 11 - 5
resources/views/app/generic-bills/add-bill-form/_default-fields.blade.php

@@ -1,7 +1,9 @@
-<div class="mb-2 min-width-300px">
-    <label for="" class="text-secondary text-sm">Company Pro</label>
-    <div class="p-2 border bg-light rounded">{{$genericCompanyPro->pro->displayName()}} / {{$genericCompanyPro->company->name}}</div>
-</div>
+@if($pro && $pro->pro_type === 'ADMIN')
+    <div class="mb-2 min-width-300px">
+        <label for="" class="text-secondary text-sm">Company Pro</label>
+        <div class="p-2 border bg-light rounded">{{$genericCompanyPro->pro->displayName()}} / {{$genericCompanyPro->company->name}}</div>
+    </div>
+@endif
 <input type="hidden" name="genericCompanyProUid" value="{{$genericCompanyPro->uid}}">
 @if(@$note)
     <input type="hidden" name="optionalNoteUid" value="{{$note->uid}}">
@@ -37,7 +39,11 @@
     </div>
 @endif
 <div class="mb-2">
-    <?php $maxMinutes = 240; ?>
+    <?php
+    if(!@$maxMinutes) {
+        $maxMinutes = 240;
+    }
+    ?>
     <label for="" class="text-secondary text-sm">Minutes</label>
     <div class="mb-2">
         <select name="numberOfUnits" class="form-control form-control-sm"

+ 14 - 0
resources/views/app/generic-bills/add-bill-form/_default-script.blade.php

@@ -20,6 +20,20 @@
                         maxNumberOf5Minutes = Math.ceil(maxNABillableAmount / amountPer5Minutes),
                         maxHours = (maxNumberOf5Minutes * 5) / 60,
                         unitsSelect = $(_trigger).closest('form').find('[name="numberOfUnits"]');
+
+                    // CRITERIA TO BILL UP TO 60 MINS. is note.hcp_pro_id == client.mcp_pro_id AND note.wasCmSetupPerformed IS TRUE
+                    $('.cm-setup-alert').remove();
+                    @if(@$note && @$patient && $note->hcp_pro_id === $patient->mcp_pro_id && $note->was_cm_setup_performed)
+                    maxHours = 1;
+                    @endif
+                    @if(@$note && @$patient && $note->hcp_pro_id === $patient->mcp_pro_id && !$note->was_cm_setup_performed)
+                    $('<div/>')
+                        .addClass('alert alert-warning my-2 cm-setup-alert border border-warning p-2')
+                        .html('<div class="mb-2">CCM setup may have been performed, but has not been marked as such in the note.</div>' +
+                            'Please ask the HCP if they need to do that, and then you can bill up to 60 mins. because patient needs education re: CM')
+                        .insertAfter(unitsSelect);
+                    @endif
+
                     unitsSelect.find('option').each(function () {
                         if (this.value) {
                             if (+this.value > maxHours) {

+ 10 - 1
resources/views/app/generic-bills/inline.blade.php

@@ -40,8 +40,8 @@ $genericBills = genericBills($pro, @$patient, @$entityType, @$entityUid);
                     <th class="border-bottom-0 screen-only">Total</th>
                     <th class="border-bottom-0">Sign</th>
                     <th class="border-bottom-0">Cancellation</th>
-                    @if($pro->pro_type === 'ADMIN')
                     <th class="border-bottom-0">Verification</th>
+                    @if($pro->pro_type === 'ADMIN')
                     <th class="border-bottom-0 screen-only">Payment</th>
                     @endif
                 </tr>
@@ -206,6 +206,15 @@ $genericBills = genericBills($pro, @$patient, @$entityType, @$entityUid);
                             @endif
 
                         </td>
+                        <td> <!-- verification -->
+                            @if(!$bill->is_cancelled)
+                                @if(!$bill->is_verified)
+                                    <div class="text-warning-mellow font-weight-bold">Not Verified</div>
+                                @else
+                                    <div class="text-info font-weight-bold"><i class="fa fa-check"></i> Verified</div>
+                                @endif
+                            @endif
+                        </td>
                         @if($pro->pro_type === 'ADMIN')
                         <td> <!-- verification -->
                             @if(!$bill->is_cancelled)

+ 33 - 17
resources/views/app/guest/appointment-confirmation.blade.php

@@ -25,27 +25,43 @@
                         </p>
                     </div>
 
-                    <div class="form-group">
-                        <p>Please confirm your appointment</p>
-                    </div>
-
-                    <div class="form-group">
-                        <div class="check d-flex align-items-center mb-2">
-                            <input type="radio" required name="decision" value="ACCEPT" id="appointment_confirmation_accept" class="check-input my-0 mr-2">
-                            <label for="appointment_confirmation_accept" class="check-label my-0">Accept - <b>I confirm my availability at the above mentioned date/time</b></label>
+                    @if(count($appointment->confirmationDecisions))
+                        <p class="mb-2 text-secondary font-weight-bold">Appointment status history</p>
+                        <div class="bg-light px-2 pt-2 border rounded mb-3">
+                            @foreach($appointment->confirmationDecisions as $decision)
+                                <div class="mb-2"><b>{{$decision->accepted_or_rejected_or_waived}}</b> on <b>{{friendlier_date_time($decision->created_at)}}</b>
+                                    @if($decision->session && $decision->session->pro)
+                                        by <b>{{$decision->session->pro->displayName()}}</b>
+                                    @elseif($decision->session && $decision->session->client)
+                                        by <b>{{$decision->session->client->displayName()}}</b>
+                                    @endif
+                                </div>
+                            @endforeach
                         </div>
-                        <div class="check d-flex align-items-center">
-                            <input type="radio" required name="decision" value="REJECT" id="appointment_confirmation_reject" class="check-input my-0 mr-2">
-                            <label for="appointment_confirmation_reject" class="check-label my-0">Reject - <b>I do not want an appointment at the above mentioned date/time</b></label>
+                        <p class="text-secondary font-weight-bold mb-2">Update appointment status</p>
+                    @else
+                        <p class="text-secondary font-weight-bold mb-2">Please confirm your appointment</p>
+                    @endif
+
+                    <div class="bg-light px-2 pt-2 border rounded mb-3">
+                        <div class="form-group mb-2">
+                            <div class="check d-flex align-items-center mb-2">
+                                <input type="radio" required name="decision" value="ACCEPT" id="appointment_confirmation_accept" class="check-input my-0 mr-2">
+                                <label for="appointment_confirmation_accept" class="check-label my-0">Accept - <b>I confirm my availability at the above mentioned date/time</b></label>
+                            </div>
+                            <div class="check d-flex align-items-center">
+                                <input type="radio" required name="decision" value="REJECT" id="appointment_confirmation_reject" class="check-input my-0 mr-2">
+                                <label for="appointment_confirmation_reject" class="check-label my-0">Reject - <b>I do not want an appointment at the above mentioned date/time</b></label>
+                            </div>
                         </div>
-                    </div>
 
-                    <div class="form-group">
-                        <textarea name="memo" class="form-control form-control-sm" placeholder="Any additional information / reason in case you are rejecting the appointment"></textarea>
-                    </div>
+                        <div class="form-group mb-2">
+                            <textarea name="memo" class="form-control form-control-sm" placeholder="Any additional information / reason in case you are rejecting the appointment"></textarea>
+                        </div>
 
-                    <div class="form-group">
-                        <button class="btn btn-primary">Submit</button>
+                        <div class="form-group mb-2">
+                            <button class="btn btn-primary">Submit</button>
+                        </div>
                     </div>
 
                 </form>

+ 2 - 2
resources/views/app/new-non-mcn-patient.blade.php

@@ -73,7 +73,7 @@
                         </div>
                         <div class='form-group mb-3'>
                             <label class='control-label'>Payer</label>
-                            <select name="mbPayerUid" class="form-control select2">
+                            <select name="payerName" class="form-control select2">
                                 <option value="">--select--</option>
                                 @foreach($mbPayers as $mbPayer)
                                 <option value="{{$mbPayer->uid}}">{{$mbPayer->name()}}</option>
@@ -82,7 +82,7 @@
                         </div>
                         <div class='form-group mb-3'>
                             <label class='control-label'>Member ID</label>
-                            <input class='form-control' type='text' name='mbPayerMemberId' required>
+                            <input class='form-control' type='text' name='payerMemberId' required>
                         </div>
                         <div class='form-group mb-3'>
                             <label class='control-label'>Initiative</label>

+ 752 - 5
resources/views/app/new-patient.blade.php

@@ -27,6 +27,43 @@
                             <label class='control-label'>Last Name *</label>
                             <input class='form-control' type='text' name='nameLast' value='' required>
                         </div>
+
+                        @if($pro->pro_type === 'ADMIN')
+                            <div class='form-group mb-3'>
+                                <label class='control-label'>MCP Pro</label>
+                                <select name="mcpProUid" class="form-control" provider-search provider-type="hcp">
+                                    <option value="">--select--</option>
+                                </select>
+                            </div>
+                            <div class='form-group mb-3'>
+                                <label class='control-label'>Default NA Pro</label>
+                                <select name="defaultNaProUid" class="form-control" provider-search provider-type="default-na">
+                                    <option value="">--select--</option>
+                                </select>
+                            </div>
+                        @elseif($pro->is_hcp === true)
+                            <div class='form-group mb-3'>
+                                <label class='control-label'>MCP Pro</label>
+                                <input type="text" class="form-control" readonly value="{{$pro->displayName()}}">
+                                <input type="hidden" name="mcpProUid" value="{{$pro->uid}}">
+                            </div>
+                        @elseif($pro->isDefaultNA())
+                            <div class='form-group mb-3'>
+                                <label class='control-label'>MCP Pro</label>
+                                <?php $teams = $pro->teamsWhereAssistant; ?>
+                                <select name="mcpProUid" class="form-control">
+                                    <option value="">--select--</option>
+                                    @foreach($teams as $team)
+                                        <option value="{{$team->mcp->uid}}">{{$team->mcp->displayName()}}</option>
+                                    @endforeach
+                                </select>
+                            </div>
+                            <div class='form-group mb-3'>
+                                <label class='control-label'>Default NA Pro</label>
+                                <input type="text" class="form-control" readonly value="{{$pro->displayName()}}">
+                                <input type="hidden" name="defaultNaProUid" value="{{$pro->uid}}">
+                            </div>
+                        @endif
 			
                         <div class='form-group mb-3'>
                             <label class='control-label'>Sex</label>
@@ -91,16 +128,726 @@
                         <div data-insurance="non-medicare" class="d-none">
                             <div class='form-group mb-3'>
                                 <label class='control-label d-block'>Payer</label>
-                                <select name="mbPayerUid" class="form-control select2">
+                                <select name="payerName" class="form-control select2">
                                     <option value="">--select--</option>
-                                    @foreach($mbPayers as $mbPayer)
-                                        <option value="{{$mbPayer->uid}}">{{$mbPayer->name()}}</option>
-                                    @endforeach
+                                    <option value="1199SEIU">1199SEIU</option>
+                                    <option value="1st Agency">1st Agency</option>
+                                    <option value="20/20 Eyecare Plan">20/20 Eyecare Plan</option>
+                                    <option value="AARP">AARP</option>
+                                    <option value="ACE">ACE</option>
+                                    <option value="AIG">AIG</option>
+                                    <option value="APWU">APWU</option>
+                                    <option value="ATRIO Health Plans">ATRIO Health Plans</option>
+                                    <option value="AVMA Life">AVMA Life</option>
+                                    <option value="Absolute Total Care">Absolute Total Care</option>
+                                    <option value="Access Medicare (NY)">Access Medicare (NY)</option>
+                                    <option value="Accountable Health Plan of Ohio">Accountable Health Plan of Ohio</option>
+                                    <option value="Advanced Health">Advanced Health</option>
+                                    <option value="AdvantageMD">AdvantageMD</option>
+                                    <option value="Advantica">Advantica</option>
+                                    <option value="Advent Health">Advent Health</option>
+                                    <option value="Adventist Health">Adventist Health</option>
+                                    <option value="Advocate Health Care">Advocate Health Care</option>
+                                    <option value="Aetna">Aetna</option>
+                                    <option value="Aetna Better Health">Aetna Better Health</option>
+                                    <option value="Affinity Health Plan">Affinity Health Plan</option>
+                                    <option value="AgeWell New York">AgeWell New York</option>
+                                    <option value="Agile Health Insurance">Agile Health Insurance</option>
+                                    <option value="Alameda Alliance for Health">Alameda Alliance for Health</option>
+                                    <option value="Aliera Health Care">Aliera Health Care</option>
+                                    <option value="Alignment Health Plan">Alignment Health Plan</option>
+                                    <option value="All Savers Insurance">All Savers Insurance</option>
+                                    <option value="AllCare Health">AllCare Health</option>
+                                    <option value="AllState">AllState</option>
+                                    <option value="AllWays Health Partners">AllWays Health Partners</option>
+                                    <option value="Allegiance Life and Health">Allegiance Life and Health</option>
+                                    <option value="Alliant Health Plans">Alliant Health Plans</option>
+                                    <option value="Allianz Worldwide Care">Allianz Worldwide Care</option>
+                                    <option value="Allwell">Allwell</option>
+                                    <option value="AlohaCare">AlohaCare</option>
+                                    <option value="AlphaCare">AlphaCare</option>
+                                    <option value="AltaMed Senior BuenaCare (PACE)">AltaMed Senior BuenaCare (PACE)</option>
+                                    <option value="Altius (Coventry Health Care)">Altius (Coventry Health Care)</option>
+                                    <option value="AlwaysCare">AlwaysCare</option>
+                                    <option value="Ambetter">Ambetter</option>
+                                    <option value="AmeriGroup">AmeriGroup</option>
+                                    <option value="AmeriHealth">AmeriHealth</option>
+                                    <option value="AmeriHealth Caritas">AmeriHealth Caritas</option>
+                                    <option value="America's 1st Choice">America's 1st Choice</option>
+                                    <option value="American Behavioral">American Behavioral</option>
+                                    <option value="American Eldercare">American Eldercare</option>
+                                    <option value="American Healthcare Alliance">American Healthcare Alliance</option>
+                                    <option value="American Maritime Officers Plans">American Maritime Officers Plans</option>
+                                    <option value="American Republic Insurance Company">American Republic Insurance Company</option>
+                                    <option value="Amida Care">Amida Care</option>
+                                    <option value="Amplifon Hearing Health Care">Amplifon Hearing Health Care</option>
+                                    <option value="Anthem Blue Cross">Anthem Blue Cross</option>
+                                    <option value="Anthem Blue Cross Blue Shield">Anthem Blue Cross Blue Shield</option>
+                                    <option value="Apostrophe">Apostrophe</option>
+                                    <option value="ArchCare">ArchCare</option>
+                                    <option value="Arise Health Plan">Arise Health Plan</option>
+                                    <option value="Arizona Complete Health">Arizona Complete Health</option>
+                                    <option value="Arizona Foundation for Medical Care">Arizona Foundation for Medical Care</option>
+                                    <option value="Arkansas Blue Cross Blue Shield">Arkansas Blue Cross Blue Shield</option>
+                                    <option value="Arkansas Total Care">Arkansas Total Care</option>
+                                    <option value="Ascension Complete">Ascension Complete</option>
+                                    <option value="Ascension Health">Ascension Health</option>
+                                    <option value="Assurant Employee Benefits">Assurant Employee Benefits</option>
+                                    <option value="Assurant Health">Assurant Health</option>
+                                    <option value="Asuris Northwest Health">Asuris Northwest Health</option>
+                                    <option value="Aultcare">Aultcare</option>
+                                    <option value="AvMed">AvMed</option>
+                                    <option value="Avera Health Plans">Avera Health Plans</option>
+                                    <option value="Avesis">Avesis</option>
+                                    <option value="BMC HealthNet Plan">BMC HealthNet Plan</option>
+                                    <option value="Banker's Life">Banker's Life</option>
+                                    <option value="Banner Health">Banner Health</option>
+                                    <option value="Baptist Health Plan">Baptist Health Plan</option>
+                                    <option value="BayCarePlus Medicare Advantage">BayCarePlus Medicare Advantage</option>
+                                    <option value="Beacon Health Options">Beacon Health Options</option>
+                                    <option value="Beaumont Employee Health Plan">Beaumont Employee Health Plan</option>
+                                    <option value="Beech Street">Beech Street</option>
+                                    <option value="Best Choice Plus">Best Choice Plus</option>
+                                    <option value="Best Doctors Insurance">Best Doctors Insurance</option>
+                                    <option value="Best Life And Health">Best Life And Health</option>
+                                    <option value="Better Health (Florida Medicaid)">Better Health (Florida Medicaid)</option>
+                                    <option value="Bind HealthCare">Bind HealthCare</option>
+                                    <option value="Blue Choice Health Plan">Blue Choice Health Plan</option>
+                                    <option value="Blue Cross Blue Shield (BCBS)">Blue Cross Blue Shield (BCBS)</option>
+                                    <option value="Blue Cross Blue Shield Federal Employee Program">Blue Cross Blue Shield Federal Employee Program</option>
+                                    <option value="Blue Cross Blue Shield of Alabama">Blue Cross Blue Shield of Alabama</option>
+                                    <option value="Blue Cross Blue Shield of Arizona">Blue Cross Blue Shield of Arizona</option>
+                                    <option value="Blue Cross Blue Shield of Georgia">Blue Cross Blue Shield of Georgia</option>
+                                    <option value="Blue Cross Blue Shield of Illinois">Blue Cross Blue Shield of Illinois</option>
+                                    <option value="Blue Cross Blue Shield of Kansas">Blue Cross Blue Shield of Kansas</option>
+                                    <option value="Blue Cross Blue Shield of Kansas City">Blue Cross Blue Shield of Kansas City</option>
+                                    <option value="Blue Cross Blue Shield of Louisiana">Blue Cross Blue Shield of Louisiana</option>
+                                    <option value="Blue Cross Blue Shield of Massachusetts">Blue Cross Blue Shield of Massachusetts</option>
+                                    <option value="Blue Cross Blue Shield of Michigan">Blue Cross Blue Shield of Michigan</option>
+                                    <option value="Blue Cross Blue Shield of Minnesota">Blue Cross Blue Shield of Minnesota</option>
+                                    <option value="Blue Cross Blue Shield of Mississippi">Blue Cross Blue Shield of Mississippi</option>
+                                    <option value="Blue Cross Blue Shield of Montana">Blue Cross Blue Shield of Montana</option>
+                                    <option value="Blue Cross Blue Shield of Nebraska">Blue Cross Blue Shield of Nebraska</option>
+                                    <option value="Blue Cross Blue Shield of New Mexico">Blue Cross Blue Shield of New Mexico</option>
+                                    <option value="Blue Cross Blue Shield of North Carolina">Blue Cross Blue Shield of North Carolina</option>
+                                    <option value="Blue Cross Blue Shield of North Dakota">Blue Cross Blue Shield of North Dakota</option>
+                                    <option value="Blue Cross Blue Shield of Oklahoma">Blue Cross Blue Shield of Oklahoma</option>
+                                    <option value="Blue Cross Blue Shield of Rhode Island">Blue Cross Blue Shield of Rhode Island</option>
+                                    <option value="Blue Cross Blue Shield of South Carolina">Blue Cross Blue Shield of South Carolina</option>
+                                    <option value="Blue Cross Blue Shield of Tennessee">Blue Cross Blue Shield of Tennessee</option>
+                                    <option value="Blue Cross Blue Shield of Texas">Blue Cross Blue Shield of Texas</option>
+                                    <option value="Blue Cross Blue Shield of Vermont">Blue Cross Blue Shield of Vermont</option>
+                                    <option value="Blue Cross Blue Shield of Western New York">Blue Cross Blue Shield of Western New York</option>
+                                    <option value="Blue Cross Blue Shield of Wyoming">Blue Cross Blue Shield of Wyoming</option>
+                                    <option value="Blue Cross of Idaho">Blue Cross of Idaho</option>
+                                    <option value="Blue Cross of Northeastern Pennsylvania">Blue Cross of Northeastern Pennsylvania</option>
+                                    <option value="Blue Shield of California">Blue Shield of California</option>
+                                    <option value="Blue Shield of Northeastern New York">Blue Shield of Northeastern New York</option>
+                                    <option value="Brand New Day">Brand New Day</option>
+                                    <option value="Braven Health (Horizon Blue Cross Blue Shield of New Jersey)">Braven Health (Horizon Blue Cross Blue Shield of New Jersey)</option>
+                                    <option value="BridgeSpan">BridgeSpan</option>
+                                    <option value="Bridgeway Health Solutions">Bridgeway Health Solutions</option>
+                                    <option value="Bright Health">Bright Health</option>
+                                    <option value="Buckeye Health Plan">Buckeye Health Plan</option>
+                                    <option value="CBA Blue">CBA Blue</option>
+                                    <option value="CDPHP">CDPHP</option>
+                                    <option value="CHAMPVA">CHAMPVA</option>
+                                    <option value="CHP Group">CHP Group</option>
+                                    <option value="CHRISTUS Health Plan">CHRISTUS Health Plan</option>
+                                    <option value="CalOptima">CalOptima</option>
+                                    <option value="CalPERS">CalPERS</option>
+                                    <option value="CalViva Health">CalViva Health</option>
+                                    <option value="California Foundation for Medical Care">California Foundation for Medical Care</option>
+                                    <option value="California Health and Wellness">California Health and Wellness</option>
+                                    <option value="Calvos">Calvos</option>
+                                    <option value="Cambridge Health Alliance (CHA)">Cambridge Health Alliance (CHA)</option>
+                                    <option value="Capital Blue Cross">Capital Blue Cross</option>
+                                    <option value="Capital Health Plan">Capital Health Plan</option>
+                                    <option value="Care Access Health Plan">Care Access Health Plan</option>
+                                    <option value="Care Improvement Plus">Care Improvement Plus</option>
+                                    <option value="Care N' Care">Care N' Care</option>
+                                    <option value="Care1st">Care1st</option>
+                                    <option value="CareConnect">CareConnect</option>
+                                    <option value="CareFirst Blue Cross Blue Shield">CareFirst Blue Cross Blue Shield</option>
+                                    <option value="CareMore">CareMore</option>
+                                    <option value="CareOregon">CareOregon</option>
+                                    <option value="CarePartners of Connecticut">CarePartners of Connecticut</option>
+                                    <option value="CarePlus Health Plans (Florida Medicare)">CarePlus Health Plans (Florida Medicare)</option>
+                                    <option value="CareSource">CareSource</option>
+                                    <option value="Cascade Health Alliance">Cascade Health Alliance</option>
+                                    <option value="Caterpillar">Caterpillar</option>
+                                    <option value="CeltiCare Health Plan">CeltiCare Health Plan</option>
+                                    <option value="CenCal Health">CenCal Health</option>
+                                    <option value="Cenpatico">Cenpatico</option>
+                                    <option value="Centennial Care">Centennial Care</option>
+                                    <option value="Center for Elders' Independence (PACE)">Center for Elders' Independence (PACE)</option>
+                                    <option value="CenterLight Healthcare">CenterLight Healthcare</option>
+                                    <option value="Centers Plan for Healthy Living">Centers Plan for Healthy Living</option>
+                                    <option value="Centers for Medicare &amp; Medicaid Services">Centers for Medicare &amp; Medicaid Services</option>
+                                    <option value="Centivo">Centivo</option>
+                                    <option value="Centra Health">Centra Health</option>
+                                    <option value="Central California Alliance for Health">Central California Alliance for Health</option>
+                                    <option value="Central Health Plan of California">Central Health Plan of California</option>
+                                    <option value="Century Healthcare - CHC">Century Healthcare - CHC</option>
+                                    <option value="Children's Community Health Plan">Children's Community Health Plan</option>
+                                    <option value="Children's Medical Center Health Plan">Children's Medical Center Health Plan</option>
+                                    <option value="Children's Medical Services (CMS)">Children's Medical Services (CMS)</option>
+                                    <option value="Chinese Community Health Plan">Chinese Community Health Plan</option>
+                                    <option value="Choice Care Network">Choice Care Network</option>
+                                    <option value="Christian Healthcare Ministries">Christian Healthcare Ministries</option>
+                                    <option value="Cigna">Cigna</option>
+                                    <option value="Cigna-HealthSpring">Cigna-HealthSpring</option>
+                                    <option value="Clarion Health">Clarion Health</option>
+                                    <option value="Clark County Self-Funded Health">Clark County Self-Funded Health</option>
+                                    <option value="Clear Spring Health">Clear Spring Health</option>
+                                    <option value="Clements Worldwide">Clements Worldwide</option>
+                                    <option value="Cleveland Clinic Employee Health Plan">Cleveland Clinic Employee Health Plan</option>
+                                    <option value="Clover Health">Clover Health</option>
+                                    <option value="Cofinity">Cofinity</option>
+                                    <option value="Colorado Access">Colorado Access</option>
+                                    <option value="Columbia Pacific CCO">Columbia Pacific CCO</option>
+                                    <option value="Columbia United Providers">Columbia United Providers</option>
+                                    <option value="ComPsych">ComPsych</option>
+                                    <option value="Common Ground Healthcare Cooperative">Common Ground Healthcare Cooperative</option>
+                                    <option value="Commonwealth Care Alliance">Commonwealth Care Alliance</option>
+                                    <option value="Community Behavioral Health">Community Behavioral Health</option>
+                                    <option value="Community Care Alliance of Illinois">Community Care Alliance of Illinois</option>
+                                    <option value="Community Care Associates">Community Care Associates</option>
+                                    <option value="Community Care Behavioral Health Organization">Community Care Behavioral Health Organization</option>
+                                    <option value="Community Care Plan">Community Care Plan</option>
+                                    <option value="Community Care of North Carolina">Community Care of North Carolina</option>
+                                    <option value="Community Eye Care">Community Eye Care</option>
+                                    <option value="Community First Health Plans">Community First Health Plans</option>
+                                    <option value="Community Health Choice">Community Health Choice</option>
+                                    <option value="Community Health Group">Community Health Group</option>
+                                    <option value="Community Health Options">Community Health Options</option>
+                                    <option value="Community Health Partners">Community Health Partners</option>
+                                    <option value="Community Health Plan of Washington">Community Health Plan of Washington</option>
+                                    <option value="CommunityCare of Oklahoma">CommunityCare of Oklahoma</option>
+                                    <option value="CompBenefits">CompBenefits</option>
+                                    <option value="Companion Life">Companion Life</option>
+                                    <option value="Comprehensive Health Insurance Plan (CHIP) of Illinois">Comprehensive Health Insurance Plan (CHIP) of Illinois</option>
+                                    <option value="Comprehensive Medical and Dental Program (CMDP)">Comprehensive Medical and Dental Program (CMDP)</option>
+                                    <option value="Connect Care">Connect Care</option>
+                                    <option value="ConnectiCare">ConnectiCare</option>
+                                    <option value="Consolidated Health Plans">Consolidated Health Plans</option>
+                                    <option value="Constitution Life">Constitution Life</option>
+                                    <option value="Consumer Health Network">Consumer Health Network</option>
+                                    <option value="Contra Costa Health Plan">Contra Costa Health Plan</option>
+                                    <option value="Cook Children's Health Plan">Cook Children's Health Plan</option>
+                                    <option value="Coordinated Care Health">Coordinated Care Health</option>
+                                    <option value="Corvel">Corvel</option>
+                                    <option value="CountyCare (Cook County)">CountyCare (Cook County)</option>
+                                    <option value="Coventry Health Care">Coventry Health Care</option>
+                                    <option value="Cox HealthPlans">Cox HealthPlans</option>
+                                    <option value="Create">Create</option>
+                                    <option value="Crystal Run Health Plans">Crystal Run Health Plans</option>
+                                    <option value="Culinary Health Fund">Culinary Health Fund</option>
+                                    <option value="DAKOTACARE">DAKOTACARE</option>
+                                    <option value="DC Medicaid">DC Medicaid</option>
+                                    <option value="DMC Care">DMC Care</option>
+                                    <option value="DOCS (Doctors of the Oregon South Coast)">DOCS (Doctors of the Oregon South Coast)</option>
+                                    <option value="DavidShield">DavidShield</option>
+                                    <option value="Davis Vision">Davis Vision</option>
+                                    <option value="Deaconess Health Plans">Deaconess Health Plans</option>
+                                    <option value="Dean Health Plan">Dean Health Plan</option>
+                                    <option value="Denver Health Medical Plan">Denver Health Medical Plan</option>
+                                    <option value="Department of Medical Assistance Services">Department of Medical Assistance Services</option>
+                                    <option value="Deseret Mutual">Deseret Mutual</option>
+                                    <option value="Devon Health Services">Devon Health Services</option>
+                                    <option value="Devoted Health">Devoted Health</option>
+                                    <option value="Dimension Health">Dimension Health</option>
+                                    <option value="Doctors HealthCare Plans">Doctors HealthCare Plans</option>
+                                    <option value="Driscoll Health Plan">Driscoll Health Plan</option>
+                                    <option value="EHP Significa">EHP Significa</option>
+                                    <option value="EMI Health">EMI Health</option>
+                                    <option value="ESSENCE Healthcare">ESSENCE Healthcare</option>
+                                    <option value="Eastern Oregon Coordinated Care Organization">Eastern Oregon Coordinated Care Organization</option>
+                                    <option value="Easy Choice Health Plan (California)">Easy Choice Health Plan (California)</option>
+                                    <option value="Easy Choice Health Plan of New York">Easy Choice Health Plan of New York</option>
+                                    <option value="El Paso First Health Plans">El Paso First Health Plans</option>
+                                    <option value="Elderplan">Elderplan</option>
+                                    <option value="EmblemHealth">EmblemHealth</option>
+                                    <option value="EmblemHealth (formerly known as GHI)">EmblemHealth (formerly known as GHI)</option>
+                                    <option value="EmblemHealth (formerly known as HIP)">EmblemHealth (formerly known as HIP)</option>
+                                    <option value="Emory Health Care Plan">Emory Health Care Plan</option>
+                                    <option value="Empire Blue Cross Blue Shield">Empire Blue Cross Blue Shield</option>
+                                    <option value="Empire BlueCross BlueShield HealthPlus">Empire BlueCross BlueShield HealthPlus</option>
+                                    <option value="Empire Plan">Empire Plan</option>
+                                    <option value="Empower Healthcare Solutions">Empower Healthcare Solutions</option>
+                                    <option value="Encore Health Network">Encore Health Network</option>
+                                    <option value="Envolve Benefit Options">Envolve Benefit Options</option>
+                                    <option value="Eon Health">Eon Health</option>
+                                    <option value="Epic Hearing Health Care">Epic Hearing Health Care</option>
+                                    <option value="Erickson Advantage">Erickson Advantage</option>
+                                    <option value="EverCare">EverCare</option>
+                                    <option value="Evergreen Health Cooperative">Evergreen Health Cooperative</option>
+                                    <option value="Evolutions Healthcare Systems">Evolutions Healthcare Systems</option>
+                                    <option value="Excellus Blue Cross Blue Shield">Excellus Blue Cross Blue Shield</option>
+                                    <option value="Experience HealthND">Experience HealthND</option>
+                                    <option value="Extended Managed Long Term Care">Extended Managed Long Term Care</option>
+                                    <option value="EyeMed">EyeMed</option>
+                                    <option value="Eyetopia Vision Care">Eyetopia Vision Care</option>
+                                    <option value="Fallon Community Health Plan (FCHP)">Fallon Community Health Plan (FCHP)</option>
+                                    <option value="Family Health Network">Family Health Network</option>
+                                    <option value="FamilyCare Health Plans">FamilyCare Health Plans</option>
+                                    <option value="Fidelis Care (NY)">Fidelis Care (NY)</option>
+                                    <option value="First Choice Health">First Choice Health</option>
+                                    <option value="First Choice Health Plan of Mississippi">First Choice Health Plan of Mississippi</option>
+                                    <option value="First Health (Coventry Health Care)">First Health (Coventry Health Care)</option>
+                                    <option value="FirstCare Health Plans">FirstCare Health Plans</option>
+                                    <option value="FirstCarolinaCare">FirstCarolinaCare</option>
+                                    <option value="Florida Blue: Blue Cross Blue Shield of Florida">Florida Blue: Blue Cross Blue Shield of Florida</option>
+                                    <option value="Florida Community Care">Florida Community Care</option>
+                                    <option value="Florida Health Care Plans">Florida Health Care Plans</option>
+                                    <option value="Florida Health Partners">Florida Health Partners</option>
+                                    <option value="Florida Hospital Healthcare System (FHHS)">Florida Hospital Healthcare System (FHHS)</option>
+                                    <option value="Florida KidCare">Florida KidCare</option>
+                                    <option value="Fort Bend County Indigent Health Care">Fort Bend County Indigent Health Care</option>
+                                    <option value="Fortified Provider Network">Fortified Provider Network</option>
+                                    <option value="Freedom Health">Freedom Health</option>
+                                    <option value="Fresenius Health Plans">Fresenius Health Plans</option>
+                                    <option value="Friday Health Plans">Friday Health Plans</option>
+                                    <option value="GEHA">GEHA</option>
+                                    <option value="GEMCare Health Plan">GEMCare Health Plan</option>
+                                    <option value="GWH-Cigna (formerly Great West Healthcare)">GWH-Cigna (formerly Great West Healthcare)</option>
+                                    <option value="Galaxy Health">Galaxy Health</option>
+                                    <option value="Gateway Health">Gateway Health</option>
+                                    <option value="Geisinger Health Plan">Geisinger Health Plan</option>
+                                    <option value="General Vision Services (GVS)">General Vision Services (GVS)</option>
+                                    <option value="GeoBlue">GeoBlue</option>
+                                    <option value="Gilsbar 360 Alliance">Gilsbar 360 Alliance</option>
+                                    <option value="Global Health">Global Health</option>
+                                    <option value="Gold Coast Health Plan">Gold Coast Health Plan</option>
+                                    <option value="Golden Rule">Golden Rule</option>
+                                    <option value="Golden State Medicare Health Plan">Golden State Medicare Health Plan</option>
+                                    <option value="Green Mountain Care (Vermont)">Green Mountain Care (Vermont)</option>
+                                    <option value="Group Health Cooperative">Group Health Cooperative</option>
+                                    <option value="Group Health Cooperative of Eau Claire">Group Health Cooperative of Eau Claire</option>
+                                    <option value="Group Health Cooperative of South Central Wisconsin">Group Health Cooperative of South Central Wisconsin</option>
+                                    <option value="Guardian">Guardian</option>
+                                    <option value="Gundersen Health Plan">Gundersen Health Plan</option>
+                                    <option value="HAP (Health Alliance Plan)">HAP (Health Alliance Plan)</option>
+                                    <option value="HAP Midwest Health Plan">HAP Midwest Health Plan</option>
+                                    <option value="HFN">HFN</option>
+                                    <option value="HFS Medical Benefits">HFS Medical Benefits</option>
+                                    <option value="HUSKY Health">HUSKY Health</option>
+                                    <option value="Hamaspik Choice">Hamaspik Choice</option>
+                                    <option value="Harken Health">Harken Health</option>
+                                    <option value="Harmony Health Plan">Harmony Health Plan</option>
+                                    <option value="Harvard Pilgrim Health Care">Harvard Pilgrim Health Care</option>
+                                    <option value="Hawaii Medical Assurance Association (HMAA)">Hawaii Medical Assurance Association (HMAA)</option>
+                                    <option value="Hawaii Medical Service Association (HMSA)">Hawaii Medical Service Association (HMSA)</option>
+                                    <option value="Health Alliance">Health Alliance</option>
+                                    <option value="Health Choice Arizona">Health Choice Arizona</option>
+                                    <option value="Health First (FL)">Health First (FL)</option>
+                                    <option value="Health First Colorado">Health First Colorado</option>
+                                    <option value="Health First Health Plans (Florida)">Health First Health Plans (Florida)</option>
+                                    <option value="Health Net">Health Net</option>
+                                    <option value="Health New England">Health New England</option>
+                                    <option value="Health Partners Plans (Pennsylvania)">Health Partners Plans (Pennsylvania)</option>
+                                    <option value="Health Plan of Nevada">Health Plan of Nevada</option>
+                                    <option value="Health Plan of San Joaquin">Health Plan of San Joaquin</option>
+                                    <option value="Health Plan of San Mateo">Health Plan of San Mateo</option>
+                                    <option value="Health Plus">Health Plus</option>
+                                    <option value="Health Share of Oregon">Health Share of Oregon</option>
+                                    <option value="Health Sun">Health Sun</option>
+                                    <option value="HealthChoice Oklahoma">HealthChoice Oklahoma</option>
+                                    <option value="HealthChoice of Michigan">HealthChoice of Michigan</option>
+                                    <option value="HealthFirst (NY)">HealthFirst (NY)</option>
+                                    <option value="HealthNow">HealthNow</option>
+                                    <option value="HealthPartners">HealthPartners</option>
+                                    <option value="HealthScope Benefits">HealthScope Benefits</option>
+                                    <option value="HealthSmart">HealthSmart</option>
+                                    <option value="HealthTeam Advantage">HealthTeam Advantage</option>
+                                    <option value="Healthcare Highways Health Plan">Healthcare Highways Health Plan</option>
+                                    <option value="Healthlink">Healthlink</option>
+                                    <option value="Healthy Texas Women">Healthy Texas Women</option>
+                                    <option value="HealthyCT">HealthyCT</option>
+                                    <option value="Hear In America">Hear In America</option>
+                                    <option value="Hennepin Health">Hennepin Health</option>
+                                    <option value="Heritage Vision Plans">Heritage Vision Plans</option>
+                                    <option value="Highmark Blue Cross Blue Shield">Highmark Blue Cross Blue Shield</option>
+                                    <option value="Highmark Blue Cross Blue Shield of Delaware">Highmark Blue Cross Blue Shield of Delaware</option>
+                                    <option value="Highmark Blue Shield">Highmark Blue Shield</option>
+                                    <option value="Highmark BlueCross BlueShield of West Virginia">Highmark BlueCross BlueShield of West Virginia</option>
+                                    <option value="Hillsborough Health Care Plan">Hillsborough Health Care Plan</option>
+                                    <option value="Home State Health Plan">Home State Health Plan</option>
+                                    <option value="Hometown Health">Hometown Health</option>
+                                    <option value="Horizon Blue Cross Blue Shield of New Jersey">Horizon Blue Cross Blue Shield of New Jersey</option>
+                                    <option value="Horizon Blue Cross Blue Shield of New Jersey For Novartis">Horizon Blue Cross Blue Shield of New Jersey For Novartis</option>
+                                    <option value="Horizon NJ Health">Horizon NJ Health</option>
+                                    <option value="Hudson Health Plan">Hudson Health Plan</option>
+                                    <option value="Humana">Humana</option>
+                                    <option value="Humana Behavioral Health (LifeSynch)">Humana Behavioral Health (LifeSynch)</option>
+                                    <option value="IHC Health Solutions">IHC Health Solutions</option>
+                                    <option value="IMS (Independent Medical Systems)">IMS (Independent Medical Systems)</option>
+                                    <option value="IU Health Plans (Indiana University Health)">IU Health Plans (Indiana University Health)</option>
+                                    <option value="Illinicare Health">Illinicare Health</option>
+                                    <option value="Illinois' Primary Care Case Management (PCCM)">Illinois' Primary Care Case Management (PCCM)</option>
+                                    <option value="Imagine Health">Imagine Health</option>
+                                    <option value="Imperial Health Plan of California">Imperial Health Plan of California</option>
+                                    <option value="Imperial Insurance Company of Texas">Imperial Insurance Company of Texas</option>
+                                    <option value="Independence Blue Cross">Independence Blue Cross</option>
+                                    <option value="Independence Care System">Independence Care System</option>
+                                    <option value="Independent Health">Independent Health</option>
+                                    <option value="Indiana Medicaid">Indiana Medicaid</option>
+                                    <option value="Ingham Health Plan">Ingham Health Plan</option>
+                                    <option value="Inland Empire Health Plan">Inland Empire Health Plan</option>
+                                    <option value="Innovation Health">Innovation Health</option>
+                                    <option value="Integra">Integra</option>
+                                    <option value="Inter Valley Health Plan">Inter Valley Health Plan</option>
+                                    <option value="InterCommunity Health Network CCO">InterCommunity Health Network CCO</option>
+                                    <option value="Intergroup Services">Intergroup Services</option>
+                                    <option value="Iowa MediPASS">Iowa MediPASS</option>
+                                    <option value="Iowa Total Care">Iowa Total Care</option>
+                                    <option value="Itasca Medical Care">Itasca Medical Care</option>
+                                    <option value="Jackson Care Connect">Jackson Care Connect</option>
+                                    <option value="Jackson Health Plan">Jackson Health Plan</option>
+                                    <option value="Jai Medical Systems">Jai Medical Systems</option>
+                                    <option value="Johns Hopkins Employer Health Programs">Johns Hopkins Employer Health Programs</option>
+                                    <option value="KPS Health Plans">KPS Health Plans</option>
+                                    <option value="Kaiser Permanente">Kaiser Permanente</option>
+                                    <option value="Kansas HealthWave">Kansas HealthWave</option>
+                                    <option value="Kansas Superior Select">Kansas Superior Select</option>
+                                    <option value="KelseyCare Advantage">KelseyCare Advantage</option>
+                                    <option value="Keystone First">Keystone First</option>
+                                    <option value="L.A. Care Health Plan">L.A. Care Health Plan</option>
+                                    <option value="L.A. Care Health Plan">L.A. Care Health Plan</option>
+                                    <option value="Land of Lincoln Health">Land of Lincoln Health</option>
+                                    <option value="Landmark Healthplan">Landmark Healthplan</option>
+                                    <option value="Lasso Healthcare">Lasso Healthcare</option>
+                                    <option value="Legacy Health">Legacy Health</option>
+                                    <option value="Lehigh Valley Health Network Health Plan">Lehigh Valley Health Network Health Plan</option>
+                                    <option value="Leon Medical Centers Health Plans">Leon Medical Centers Health Plans</option>
+                                    <option value="Liberty Health Advantage">Liberty Health Advantage</option>
+                                    <option value="Liberty HealthShare">Liberty HealthShare</option>
+                                    <option value="Liberty Mutual">Liberty Mutual</option>
+                                    <option value="LifeWise">LifeWise</option>
+                                    <option value="Lifestyle Health">Lifestyle Health</option>
+                                    <option value="Lighthouse Guild">Lighthouse Guild</option>
+                                    <option value="Lighthouse Health Plan">Lighthouse Health Plan</option>
+                                    <option value="Lincoln Financial Group">Lincoln Financial Group</option>
+                                    <option value="Longevity Health Plan">Longevity Health Plan</option>
+                                    <option value="Louisiana Healthcare Connections">Louisiana Healthcare Connections</option>
+                                    <option value="Lutheran Preferred">Lutheran Preferred</option>
+                                    <option value="MCM Maxcare">MCM Maxcare</option>
+                                    <option value="MDwise">MDwise</option>
+                                    <option value="MHNet Behavioral Health">MHNet Behavioral Health</option>
+                                    <option value="MINES &amp; Associates">MINES &amp; Associates</option>
+                                    <option value="MMM of Florida (Medicare and Much More)">MMM of Florida (Medicare and Much More)</option>
+                                    <option value="MO HealthNet">MO HealthNet</option>
+                                    <option value="MOAA (Miltary Officers Association of America)">MOAA (Miltary Officers Association of America)</option>
+                                    <option value="MVP Health Care">MVP Health Care</option>
+                                    <option value="Magellan Health">Magellan Health</option>
+                                    <option value="MagnaCare">MagnaCare</option>
+                                    <option value="Magnolia Health Plan">Magnolia Health Plan</option>
+                                    <option value="Mail Handlers Benefit Plan">Mail Handlers Benefit Plan</option>
+                                    <option value="MaineCare">MaineCare</option>
+                                    <option value="Managed Health Network (MHN)">Managed Health Network (MHN)</option>
+                                    <option value="Managed Health Services (Indiana)">Managed Health Services (Indiana)</option>
+                                    <option value="Managed Health Services (Wisconsin)">Managed Health Services (Wisconsin)</option>
+                                    <option value="Managed HealthCare Northwest">Managed HealthCare Northwest</option>
+                                    <option value="March Vision Care">March Vision Care</option>
+                                    <option value="Maricopa Health Plan">Maricopa Health Plan</option>
+                                    <option value="Martin's Point HealthCare">Martin's Point HealthCare</option>
+                                    <option value="Maryland Medical Assistance (Medicaid)">Maryland Medical Assistance (Medicaid)</option>
+                                    <option value="Maryland Physicians Care">Maryland Physicians Care</option>
+                                    <option value="MassHealth">MassHealth</option>
+                                    <option value="Massachusetts Laborers' Health &amp; Welfare Fund">Massachusetts Laborers' Health &amp; Welfare Fund</option>
+                                    <option value="Mayo Medical Plan">Mayo Medical Plan</option>
+                                    <option value="McLaren Health Plan">McLaren Health Plan</option>
+                                    <option value="MedStar Family Choice">MedStar Family Choice</option>
+                                    <option value="MedStar Select">MedStar Select</option>
+                                    <option value="Medi-Cal">Medi-Cal</option>
+                                    <option value="MediGold">MediGold</option>
+                                    <option value="MediPass">MediPass</option>
+                                    <option value="Medica">Medica</option>
+                                    <option value="Medica HealthCare Plans (Florida)">Medica HealthCare Plans (Florida)</option>
+                                    <option value="Medicaid">Medicaid</option>
+                                    <option value="Medical Eye Services (MES Vision)">Medical Eye Services (MES Vision)</option>
+                                    <option value="Medical Mutual">Medical Mutual</option>
+                                    <option value="Medicare">Medicare</option>
+                                    <option value="Memorial Healthcare System">Memorial Healthcare System</option>
+                                    <option value="Memorial Hermann">Memorial Hermann</option>
+                                    <option value="Mercy Care">Mercy Care</option>
+                                    <option value="Meridian Health Plan">Meridian Health Plan</option>
+                                    <option value="Meritain Health">Meritain Health</option>
+                                    <option value="MetLife">MetLife</option>
+                                    <option value="MetroHealth">MetroHealth</option>
+                                    <option value="MetroPlus Health Plan">MetroPlus Health Plan</option>
+                                    <option value="Metropolitan Health Plan">Metropolitan Health Plan</option>
+                                    <option value="Miami Children's Health Plan">Miami Children's Health Plan</option>
+                                    <option value="Michigan Complete Health">Michigan Complete Health</option>
+                                    <option value="Michigan No-Fault">Michigan No-Fault</option>
+                                    <option value="Minuteman Health">Minuteman Health</option>
+                                    <option value="Mississippi Division of Medicaid">Mississippi Division of Medicaid</option>
+                                    <option value="Missouri Care">Missouri Care</option>
+                                    <option value="Moda Health">Moda Health</option>
+                                    <option value="Molina Healthcare">Molina Healthcare</option>
+                                    <option value="Montana Health Cooperative">Montana Health Cooperative</option>
+                                    <option value="Montefiore HMO">Montefiore HMO</option>
+                                    <option value="Mountain Health Co-Op">Mountain Health Co-Op</option>
+                                    <option value="Multiplan PHCS">Multiplan PHCS</option>
+                                    <option value="Mutual of Omaha">Mutual of Omaha</option>
+                                    <option value="NALC Health Benefit Plan">NALC Health Benefit Plan</option>
+                                    <option value="NECA/IBEW Family Medical Care Plan">NECA/IBEW Family Medical Care Plan</option>
+                                    <option value="NY State No-Fault">NY State No-Fault</option>
+                                    <option value="NY: YourCare Health Plan">NY: YourCare Health Plan</option>
+                                    <option value="National Congress of Employers (NCE)">National Congress of Employers (NCE)</option>
+                                    <option value="National Vision Administrators">National Vision Administrators</option>
+                                    <option value="Nationwide">Nationwide</option>
+                                    <option value="Navajo Nation">Navajo Nation</option>
+                                    <option value="Nebraska Total Care (Heritage Health)">Nebraska Total Care (Heritage Health)</option>
+                                    <option value="Neighborhood Health Plan (Massachusetts)">Neighborhood Health Plan (Massachusetts)</option>
+                                    <option value="Neighborhood Health Plan of Rhode Island">Neighborhood Health Plan of Rhode Island</option>
+                                    <option value="Network Health Plan">Network Health Plan</option>
+                                    <option value="Nevada Preferred">Nevada Preferred</option>
+                                    <option value="New Directions Behavioral Health">New Directions Behavioral Health</option>
+                                    <option value="New Hampshire Healthy Families">New Hampshire Healthy Families</option>
+                                    <option value="New Mexico Health Connections">New Mexico Health Connections</option>
+                                    <option value="New York Hotel Trades Council">New York Hotel Trades Council</option>
+                                    <option value="NextLevelHealth">NextLevelHealth</option>
+                                    <option value="Nippon Life Benefits">Nippon Life Benefits</option>
+                                    <option value="North Carolina Health Choice (NCHC) for Children">North Carolina Health Choice (NCHC) for Children</option>
+                                    <option value="North Shore LIJ CareConnect">North Shore LIJ CareConnect</option>
+                                    <option value="Northland PACE">Northland PACE</option>
+                                    <option value="NovaNet">NovaNet</option>
+                                    <option value="OHMS (Oregon Health Management Services)">OHMS (Oregon Health Management Services)</option>
+                                    <option value="OSU Health Plan">OSU Health Plan</option>
+                                    <option value="Ohara, LLC">Ohara, LLC</option>
+                                    <option value="Ohio Health Choice">Ohio Health Choice</option>
+                                    <option value="OhioHealthy">OhioHealthy</option>
+                                    <option value="On Lok Lifeways">On Lok Lifeways</option>
+                                    <option value="On Lok Lifeways (PACE)">On Lok Lifeways (PACE)</option>
+                                    <option value="OneNet PPO">OneNet PPO</option>
+                                    <option value="Opticare of Utah">Opticare of Utah</option>
+                                    <option value="Optima Health">Optima Health</option>
+                                    <option value="Optimum HealthCare">Optimum HealthCare</option>
+                                    <option value="Optum Health">Optum Health</option>
+                                    <option value="Oscar Health Insurance Co.">Oscar Health Insurance Co.</option>
+                                    <option value="Oxford (UnitedHealthcare)">Oxford (UnitedHealthcare)</option>
+                                    <option value="PA Health and Wellness">PA Health and Wellness</option>
+                                    <option value="PA Medical Assistance">PA Medical Assistance</option>
+                                    <option value="PBA (Patrolmen's Benefit Association)">PBA (Patrolmen's Benefit Association)</option>
+                                    <option value="POMCO">POMCO</option>
+                                    <option value="Pacific Health Alliance">Pacific Health Alliance</option>
+                                    <option value="PacificSource Health Plans">PacificSource Health Plans</option>
+                                    <option value="Palmetto GBA">Palmetto GBA</option>
+                                    <option value="Pan-American Life Insurance Group">Pan-American Life Insurance Group</option>
+                                    <option value="Paradigm Senior Care Advantage">Paradigm Senior Care Advantage</option>
+                                    <option value="Paramount Healthcare">Paramount Healthcare</option>
+                                    <option value="Parkland Community Health Plan">Parkland Community Health Plan</option>
+                                    <option value="Parkview Total Health">Parkview Total Health</option>
+                                    <option value="Partners Health Plan">Partners Health Plan</option>
+                                    <option value="Partnership HealthPlan of California">Partnership HealthPlan of California</option>
+                                    <option value="Passport Health Plan (Kentucky)">Passport Health Plan (Kentucky)</option>
+                                    <option value="Passport To Health (Montana Medicaid)">Passport To Health (Montana Medicaid)</option>
+                                    <option value="Patient 1st (Alabama Medicaid)">Patient 1st (Alabama Medicaid)</option>
+                                    <option value="Peach State Health Plan">Peach State Health Plan</option>
+                                    <option value="PeachCare for Kids">PeachCare for Kids</option>
+                                    <option value="PennCare">PennCare</option>
+                                    <option value="Peoples Health">Peoples Health</option>
+                                    <option value="Phoenix Health Plan">Phoenix Health Plan</option>
+                                    <option value="Physician Assured Access System">Physician Assured Access System</option>
+                                    <option value="Physician Benefits Trust">Physician Benefits Trust</option>
+                                    <option value="Physicians Health Plan">Physicians Health Plan</option>
+                                    <option value="Physicians Health Plan of Northern Indiana, Inc.">Physicians Health Plan of Northern Indiana, Inc.</option>
+                                    <option value="PhysiciansCare">PhysiciansCare</option>
+                                    <option value="Piedmont Community Health Plan">Piedmont Community Health Plan</option>
+                                    <option value="Piedmont WellStar Health Plans">Piedmont WellStar Health Plans</option>
+                                    <option value="Positive Health Care">Positive Health Care</option>
+                                    <option value="Preferential Care Network">Preferential Care Network</option>
+                                    <option value="Preferred Care Partners">Preferred Care Partners</option>
+                                    <option value="PreferredOne">PreferredOne</option>
+                                    <option value="Premera Blue Cross">Premera Blue Cross</option>
+                                    <option value="Premier Health Plan">Premier Health Plan</option>
+                                    <option value="Presbyterian Health Plan/Presbyterian Insurance Company">Presbyterian Health Plan/Presbyterian Insurance Company</option>
+                                    <option value="Prestige Health Choice">Prestige Health Choice</option>
+                                    <option value="Primary Care Case Management (North Dakota Medicaid)">Primary Care Case Management (North Dakota Medicaid)</option>
+                                    <option value="Prime Health Services, Inc">Prime Health Services, Inc</option>
+                                    <option value="Prime Healthcare">Prime Healthcare</option>
+                                    <option value="PrimeWest Health">PrimeWest Health</option>
+                                    <option value="Principal Financial Group">Principal Financial Group</option>
+                                    <option value="Priority Health">Priority Health</option>
+                                    <option value="Priority Partners">Priority Partners</option>
+                                    <option value="Progressive">Progressive</option>
+                                    <option value="Prominence Health Plan">Prominence Health Plan</option>
+                                    <option value="ProviDRs Care (WPPA)">ProviDRs Care (WPPA)</option>
+                                    <option value="Providence Health Plans">Providence Health Plans</option>
+                                    <option value="Provider Partners Health Plan">Provider Partners Health Plan</option>
+                                    <option value="Public Aid (Illinois Medicaid)">Public Aid (Illinois Medicaid)</option>
+                                    <option value="Public Employees Health Program (PEHP)">Public Employees Health Program (PEHP)</option>
+                                    <option value="Puget Sound Electrical Workers Trusts">Puget Sound Electrical Workers Trusts</option>
+                                    <option value="QualCare">QualCare</option>
+                                    <option value="QualChoice Arkansas">QualChoice Arkansas</option>
+                                    <option value="Quality Health Plans of New York">Quality Health Plans of New York</option>
+                                    <option value="Quartz">Quartz</option>
+                                    <option value="Quest Behavioral Health">Quest Behavioral Health</option>
+                                    <option value="Quiktrip">Quiktrip</option>
+                                    <option value="RLI Indemnity Company">RLI Indemnity Company</option>
+                                    <option value="Regence Blue Cross Blue Shield">Regence Blue Cross Blue Shield</option>
+                                    <option value="Regent Insurance">Regent Insurance</option>
+                                    <option value="Reliance Medicare Advantage">Reliance Medicare Advantage</option>
+                                    <option value="Renaissance">Renaissance</option>
+                                    <option value="Republic-Franklin Insurance">Republic-Franklin Insurance</option>
+                                    <option value="RiverLink Health">RiverLink Health</option>
+                                    <option value="RiverSpring Health Plans">RiverSpring Health Plans</option>
+                                    <option value="Riverside Health">Riverside Health</option>
+                                    <option value="Rockefeller Health Plan">Rockefeller Health Plan</option>
+                                    <option value="Rocky Mountain Health Plans">Rocky Mountain Health Plans</option>
+                                    <option value="SAG AFTRA Health Plan">SAG AFTRA Health Plan</option>
+                                    <option value="SAMBA">SAMBA</option>
+                                    <option value="SCAN Health Plan">SCAN Health Plan</option>
+                                    <option value="SIHO Insurance Services">SIHO Insurance Services</option>
+                                    <option value="SSM Health Care">SSM Health Care</option>
+                                    <option value="Sagamore Health Network">Sagamore Health Network</option>
+                                    <option value="Samaritan Health Plan Operations">Samaritan Health Plan Operations</option>
+                                    <option value="San Francisco Health Plan">San Francisco Health Plan</option>
+                                    <option value="Sanford Health Plan">Sanford Health Plan</option>
+                                    <option value="Santa Clara Family Health Plan">Santa Clara Family Health Plan</option>
+                                    <option value="Scott &amp; White Health Plan">Scott &amp; White Health Plan</option>
+                                    <option value="Security Health Plan of Wisconsin, Inc.">Security Health Plan of Wisconsin, Inc.</option>
+                                    <option value="Select Care">Select Care</option>
+                                    <option value="Select Health Network">Select Health Network</option>
+                                    <option value="Select Health of South Carolina">Select Health of South Carolina</option>
+                                    <option value="SelectHealth">SelectHealth</option>
+                                    <option value="Sendero Health Plans">Sendero Health Plans</option>
+                                    <option value="Seneca Insurance">Seneca Insurance</option>
+                                    <option value="Senior Dimensions">Senior Dimensions</option>
+                                    <option value="Senior Whole Health">Senior Whole Health</option>
+                                    <option value="Sentry Insurance">Sentry Insurance</option>
+                                    <option value="Seton Health Plan">Seton Health Plan</option>
+                                    <option value="Sharp Health Plan">Sharp Health Plan</option>
+                                    <option value="Sierra Health and Life">Sierra Health and Life</option>
+                                    <option value="SightCare">SightCare</option>
+                                    <option value="SilverSummit Healthplan">SilverSummit Healthplan</option>
+                                    <option value="Simply Healthcare">Simply Healthcare</option>
+                                    <option value="Simpra Advantage">Simpra Advantage</option>
+                                    <option value="Solis Health Plans">Solis Health Plans</option>
+                                    <option value="Solstice">Solstice</option>
+                                    <option value="SoonerCare (Oklahoma Medicaid)">SoonerCare (Oklahoma Medicaid)</option>
+                                    <option value="Soundpath Health">Soundpath Health</option>
+                                    <option value="South Country Health Alliance">South Country Health Alliance</option>
+                                    <option value="South Florida Community Care Network">South Florida Community Care Network</option>
+                                    <option value="Southwestern Health Resources (SWHR)">Southwestern Health Resources (SWHR)</option>
+                                    <option value="Spectera">Spectera</option>
+                                    <option value="Standard Life and Accident Insurance Company">Standard Life and Accident Insurance Company</option>
+                                    <option value="Stanford Health Care Advantage">Stanford Health Care Advantage</option>
+                                    <option value="StarNet Insurance">StarNet Insurance</option>
+                                    <option value="State Farm®">State Farm®</option>
+                                    <option value="State National Insurance">State National Insurance</option>
+                                    <option value="Staywell Insurance">Staywell Insurance</option>
+                                    <option value="Steward Health Care Network - Health Choice Arizona">Steward Health Care Network - Health Choice Arizona</option>
+                                    <option value="Steward Health Choice">Steward Health Choice</option>
+                                    <option value="Stratose">Stratose</option>
+                                    <option value="SummaCare">SummaCare</option>
+                                    <option value="Summit Community Care">Summit Community Care</option>
+                                    <option value="Sunflower Health Plan">Sunflower Health Plan</option>
+                                    <option value="Sunrise Advantage Plan">Sunrise Advantage Plan</option>
+                                    <option value="Sunshine Health">Sunshine Health</option>
+                                    <option value="Superior HealthPlan">Superior HealthPlan</option>
+                                    <option value="Superior Vision">Superior Vision</option>
+                                    <option value="Sussex Insurance">Sussex Insurance</option>
+                                    <option value="Sutter Health Plus">Sutter Health Plus</option>
+                                    <option value="SutterSelect">SutterSelect</option>
+                                    <option value="TNUS Insurance">TNUS Insurance</option>
+                                    <option value="TakeCare">TakeCare</option>
+                                    <option value="Teachers Health Trust">Teachers Health Trust</option>
+                                    <option value="TexanPlus">TexanPlus</option>
+                                    <option value="Texas Children's Health Plan">Texas Children's Health Plan</option>
+                                    <option value="Texas Health Aetna">Texas Health Aetna</option>
+                                    <option value="Texas Kids First">Texas Kids First</option>
+                                    <option value="The HSC Health Care System">The HSC Health Care System</option>
+                                    <option value="The Hartford">The Hartford</option>
+                                    <option value="The Health Plan of the Upper Ohio Valley, Inc.">The Health Plan of the Upper Ohio Valley, Inc.</option>
+                                    <option value="Three Rivers Providers Network (TRPN)">Three Rivers Providers Network (TRPN)</option>
+                                    <option value="Total Health Care">Total Health Care</option>
+                                    <option value="Touchstone">Touchstone</option>
+                                    <option value="Transamerica">Transamerica</option>
+                                    <option value="Travelers">Travelers</option>
+                                    <option value="Tricare">Tricare</option>
+                                    <option value="Trillium Community Health Plan">Trillium Community Health Plan</option>
+                                    <option value="Trilogy Health Insurance">Trilogy Health Insurance</option>
+                                    <option value="Triple-S Salud: Blue Cross Blue Shield of Puerto Rico">Triple-S Salud: Blue Cross Blue Shield of Puerto Rico</option>
+                                    <option value="Triwest Healthcare Alliance">Triwest Healthcare Alliance</option>
+                                    <option value="TrueHealth New Mexico">TrueHealth New Mexico</option>
+                                    <option value="Trusted Health Plan">Trusted Health Plan</option>
+                                    <option value="Tuality Health Alliance">Tuality Health Alliance</option>
+                                    <option value="Tufts Health Freedom Plan">Tufts Health Freedom Plan</option>
+                                    <option value="Tufts Health Plan">Tufts Health Plan</option>
+                                    <option value="UCHP (University of Chicago Health Plan)">UCHP (University of Chicago Health Plan)</option>
+                                    <option value="UCare">UCare</option>
+                                    <option value="UHA Health Insurance">UHA Health Insurance</option>
+                                    <option value="ULLICO Casualty Company">ULLICO Casualty Company</option>
+                                    <option value="UPMC Health Plan">UPMC Health Plan</option>
+                                    <option value="US Family Health Plan">US Family Health Plan</option>
+                                    <option value="US Health Group">US Health Group</option>
+                                    <option value="USA Managed Care Organization">USA Managed Care Organization</option>
+                                    <option value="USAble Mutual Insurance Company">USAble Mutual Insurance Company</option>
+                                    <option value="Ultimate Health Plans">Ultimate Health Plans</option>
+                                    <option value="Umpqua Health Alliance">Umpqua Health Alliance</option>
+                                    <option value="UniCare">UniCare</option>
+                                    <option value="Uniform Medical Plan">Uniform Medical Plan</option>
+                                    <option value="Union Eye Care">Union Eye Care</option>
+                                    <option value="Union Health Services, Inc">Union Health Services, Inc</option>
+                                    <option value="Union Plans">Union Plans</option>
+                                    <option value="United American">United American</option>
+                                    <option value="United Behavioral Health">United Behavioral Health</option>
+                                    <option value="UnitedHealthOne">UnitedHealthOne</option>
+                                    <option value="UnitedHealthcare">UnitedHealthcare</option>
+                                    <option value="UnitedHealthcare Community Plan">UnitedHealthcare Community Plan</option>
+                                    <option value="UnitedHealthcare Oxford">UnitedHealthcare Oxford</option>
+                                    <option value="Unity Health Insurance">Unity Health Insurance</option>
+                                    <option value="Univera Healthcare">Univera Healthcare</option>
+                                    <option value="Universal American">Universal American</option>
+                                    <option value="Universal Underwriters Insurance">Universal Underwriters Insurance</option>
+                                    <option value="University Hospitals (Health Design Plus)">University Hospitals (Health Design Plus)</option>
+                                    <option value="University Physician Network (UPN)">University Physician Network (UPN)</option>
+                                    <option value="University of Arizona Health Plans">University of Arizona Health Plans</option>
+                                    <option value="University of Maryland Health Advantage">University of Maryland Health Advantage</option>
+                                    <option value="University of Maryland Health Partners">University of Maryland Health Partners</option>
+                                    <option value="University of Utah Health Plans">University of Utah Health Plans</option>
+                                    <option value="Upper Peninsula Health Plan">Upper Peninsula Health Plan</option>
+                                    <option value="VNS Choice Health Plans">VNS Choice Health Plans</option>
+                                    <option value="VSP">VSP</option>
+                                    <option value="Valley Forge Insurance">Valley Forge Insurance</option>
+                                    <option value="Valley Health Plan">Valley Health Plan</option>
+                                    <option value="Valor Health Plan">Valor Health Plan</option>
+                                    <option value="Vantage Health Plan, Inc.">Vantage Health Plan, Inc.</option>
+                                    <option value="Ventura County Health Care Plan">Ventura County Health Care Plan</option>
+                                    <option value="Vibra Health Plan">Vibra Health Plan</option>
+                                    <option value="VillageCareMax">VillageCareMax</option>
+                                    <option value="Virginia Coordinated Care (VCC)">Virginia Coordinated Care (VCC)</option>
+                                    <option value="Virginia Health Network">Virginia Health Network</option>
+                                    <option value="Virginia Premier Health Plan">Virginia Premier Health Plan</option>
+                                    <option value="Vision Benefits of America">Vision Benefits of America</option>
+                                    <option value="Vision Care Direct">Vision Care Direct</option>
+                                    <option value="Vision Plan of America">Vision Plan of America</option>
+                                    <option value="Viva Health Plan">Viva Health Plan</option>
+                                    <option value="Vivida Health">Vivida Health</option>
+                                    <option value="Volusia Health Network">Volusia Health Network</option>
+                                    <option value="Vytra">Vytra</option>
+                                    <option value="WEA Trust">WEA Trust</option>
+                                    <option value="WPS Health Plan">WPS Health Plan</option>
+                                    <option value="WRM America Indemnity Company">WRM America Indemnity Company</option>
+                                    <option value="Well Sense Health Plan">Well Sense Health Plan</option>
+                                    <option value="WellFirst Health">WellFirst Health</option>
+                                    <option value="Wellcare">Wellcare</option>
+                                    <option value="Wellmark Blue Cross Blue Shield">Wellmark Blue Cross Blue Shield</option>
+                                    <option value="West American Insurance">West American Insurance</option>
+                                    <option value="West Virginia Senior Advantage">West Virginia Senior Advantage</option>
+                                    <option value="Western Health Advantage">Western Health Advantage</option>
+                                    <option value="Western Sky Community Care">Western Sky Community Care</option>
+                                    <option value="Willamette Valley Community Health">Willamette Valley Community Health</option>
+                                    <option value="Workers' Compensation">Workers' Compensation</option>
+                                    <option value="Yamhill Community Care Organization">Yamhill Community Care Organization</option>
+                                    <option value="Zenith">Zenith</option>
                                 </select>
                             </div>
                             <div class='form-group mb-3'>
                                 <label class='control-label'>Member ID</label>
-                                <input class='form-control' type='text' name='mbPayerMemberId'>
+                                <input class='form-control' type='text' name='payerMemberId'>
                             </div>
                         </div>
                         <hr class="m-neg-4">

+ 48 - 9
resources/views/app/patient/appointment-calendar.blade.php

@@ -136,16 +136,18 @@
                         Pro
                     </div>
                     <div class="col-9 font-weight-bold">
-                        <select id="addApptPro" name="proUid" provider-search required
+                        <select id="addApptPro" name="proUid" {{$pro->pro_type !== 'ADMIN' ? '' : 'provider-search'}}
                                 v-model="newAppointment.proUid"
                                 :data-pro-uid="newAppointment.proUid"
                                 no-auto-pro-suggest-init
                                 class="form-control form-control-sm">
-                            @foreach($pros as $iPro)
-                                <option value="{{$iPro->uid}}">
-                                    {{$iPro->displayName()}}
-                                </option>
-                            @endforeach
+                            @if($pro->pro_type !== 'ADMIN')
+                                @foreach($pros as $iPro)
+                                    <option value="{{$iPro->uid}}">
+                                        {{$iPro->displayName()}}
+                                    </option>
+                                @endforeach
+                            @endif
                         </select>
                     </div>
                 </div>
@@ -252,7 +254,7 @@
                         Pro
                     </div>
                     <div class="col-9 font-weight-bold">
-                        <select id="editApptPro" name="proUid" provider-search required
+                        <select id="editApptPro" name="proUid" provider-search
                                 v-model="editAppointment.proUid"
                                 :data-pro-uid="editAppointment.proUid"
                                 no-auto-pro-suggest-init
@@ -343,13 +345,16 @@
                                   v-model="editAppointment.description"></textarea>
                     </div>
                 </div>
-                <div class="d-flex align-items-center justify-content-center">
+                <div v-if="editAppointment.allowEdit" class="d-flex align-items-center justify-content-center">
                     <button class="btn btn-sm btn-primary mr-2"
                             :disabled="inProgress"
                             v-on:click.prevent="updateAppointment()">Submit</button>
                     <button class="btn btn-sm btn-default border"
                             onclick="return closeStagPopup()">Cancel</button>
                 </div>
+                <div v-else class="alert alert-secondary mb-0">
+                    You cannot make changes to this appointment.
+                </div>
                 </div>
             </form>
         </div>
@@ -393,6 +398,8 @@
                         editAppointment: {
                             proUid: '',
                             clientName: '',
+                            clientUid: '',
+                            allowEdit: true,
                             date: '',
                             startTime: '',
                             endTime: '',
@@ -655,6 +662,11 @@
                                  }
                             });
                             this.calendar.render();
+
+                            // ugly fix/hack to force scrollTime option to work
+                            setTimeout(() => {
+                                $('.fc-timeGridWeek-button').click();
+                            }, 750);
                         },
                         afterRenderingEvents: function() {
                             let self = this;
@@ -679,6 +691,13 @@
                                 }, 250);
                             }
                             @endif
+                            setTimeout(() => {
+                                $('.fc-toolbar-title .tz-display').remove();
+                                $('<span/>')
+                                    .addClass('pl-2 tz-display text-secondary')
+                                    .text('(Timezone: ' + this.timezone + ')')
+                                    .appendTo($('.fc-toolbar-title'));
+                            }, 0);
                         },
                         dateStr: function(_dateTime) {
                             return _dateTime.getFullYear() + "-" +
@@ -729,6 +748,11 @@
                             let endTime = this.timeStr(this.selectedSlot.end);
                             this.newAppointment.clientUid = this.client.uid;
                             this.newAppointment.proUid = '';
+                            @if($pro->is_hcp && $pro->is_enrolled_as_mcp)
+                                this.newAppointment.proUid = '{{$pro->uid}}';
+                            @elseif($patient->mcp)
+                                this.newAppointment.proUid = '{{$patient->mcp->uid}}';
+                            @endif
                             this.newAppointment.referringProUid = '';
                             this.newAppointment.date = this.dateStr(this.selectedSlot.start);
                             this.newAppointment.startTime = startTime === '00:00' ? '' : startTime;
@@ -774,8 +798,23 @@
                             // setup model data
                             this.inProgress = false;
                             this.editAppointment.uid = this.selectedEvent.extendedProps.appointmentUid;
-                            this.editAppointment.clientName = this.selectedEvent.extendedProps.clientName;
                             this.editAppointment.clientUid = this.selectedEvent.extendedProps.clientUid;
+                            @if($pro->isDefaultNA())
+                                this.editAppointment.allowEdit = false;
+                                this.editAppointment.clientName = this.selectedEvent.extendedProps.clientName.split(/\s+/).map(_x => _x[0]).join('');
+                                $.get('/can-access-patient/' + this.editAppointment.clientUid, _data => {
+                                    if(!hasResponseError(_data)) {
+                                        if(_data.data) {
+                                            this.editAppointment.allowEdit = true;
+                                            this.editAppointment.clientName = this.selectedEvent.extendedProps.clientName;
+                                        }
+                                    }
+                                }, 'json');
+                            @else
+                                this.editAppointment.allowEdit = true;
+                                this.editAppointment.clientName = this.selectedEvent.extendedProps.clientName;
+                            @endif
+
                             this.editAppointment.proUid = this.selectedEvent.extendedProps.proUid;
                             this.editAppointment.date = this.dateStr(this.selectedEvent.start);
                             this.editAppointment.startTime = this.timeStr(this.selectedEvent.start);

+ 1 - 1
resources/views/app/patient/canvas-sections/fhx/summary.php

@@ -47,7 +47,7 @@ $labels = [
     'cancer_uterine_ca' => 'Uterine cancer',
 ];
 
-if(!$contentData['unknown'] && !!$contentData['count']) {
+if((isset($contentData['unknown']) && !$contentData['unknown']) && !!$contentData['count']) {
     for ($i = 0; $i < $contentData['count']; $i++) {
 ?>
         <div class="<?= $i > 0 ? 'mt-2' : '' ?>">

+ 0 - 1
resources/views/app/patient/canvas-sections/rx/form.blade.php

@@ -385,7 +385,6 @@ $formID = rand(0, 100000);
                                     'terms=' + encodeURIComponent($.trim($(this).val())) +
                                     '&maxList=1' +
                                     '&ef=STRENGTHS_AND_FORMS', _data => {
-                                    console.log('ALIX', _data);
                                     if(_data && _data.length >= 1 && _data[2].STRENGTHS_AND_FORMS && _data[2].STRENGTHS_AND_FORMS[0]) {
                                         strengthElem.autocomp.setListAndField(_data[2].STRENGTHS_AND_FORMS[0], '', true);
                                     }

+ 286 - 0
resources/views/app/patient/care-month/_matrix.blade.php

@@ -0,0 +1,286 @@
+<?php
+$days = $patient->cmMeasurementsMatrix($careMonth);
+
+$performerRole = false;
+if ($pro->pro_type === 'ADMIN') {
+    $performerRole = 'ADMIN';
+} else if ($careMonth->mcp_pro_id === $pro->id) {
+    $performerRole = 'MCP';
+} else if ($careMonth->rme_pro_id === $pro->id || $careMonth->rmm_pro_id === $pro->id) {
+    $performerRole = 'NON-HCP';
+}
+
+$unstampedMCP = [];
+$unstampedNonHCP = [];
+foreach ($days as $k => $day) {
+    $unstampedMCP[$k] = [];
+    $unstampedNonHCP[$k] = [];
+    foreach ($days[$k] as $mIndex => $m) {
+        if(!$m->has_been_stamped_by_mcp) {
+            $unstampedMCP[$k][] = $m->measurement_uid;
+        }
+        if(!$m->has_been_stamped_by_non_hcp) {
+            $unstampedNonHCP[$k][] = $m->measurement_uid;
+        }
+    }
+}
+
+?>
+
+<div id="cm-matrix-{{$patient->id}}">
+<div class="d-flex align-items-baseline">
+    <a class="font-weight-bold" href="#" tab-link="matrix">Care Month Matrix</a>
+    <span class="mx-2 text-secondary text-sm">|</span>
+    <a class="" href="#" tab-link="bmi-summary">BMI/Weight Management Settings</a>
+    <span class="mx-2 text-secondary text-sm">|</span>
+    <a class="" href="#" tab-link="bp-summary">BP Management Settings</a>
+</div>
+<table class="table table-condensed table-sm table-bordered my-3 cm-tab" tab-key="matrix">
+    <thead>
+    <tr>
+        <th class="px-2 text-secondary align-bottom" rowspan="2">Date</th>
+        <th class="px-2 text-secondary border-bottom-0" colspan="4">Measurements</th>
+        <th class="px-2 text-secondary align-bottom" rowspan="2">{{$performerRole === 'ADMIN' ? 'Stamp Status' : 'Stamp + Entry'}}</th>
+        <th class="px-2 text-secondary" rowspan="2">Entries</th>
+    </tr>
+    <tr>
+        <th class="text-secondary text-sm">Time</th>
+        <th class="text-secondary text-sm">Type</th>
+        <th class="text-secondary text-sm">Value</th>
+        <th class="text-secondary text-sm">Stamp</th>
+    </tr>
+    </thead>
+    <tbody>
+    @foreach($days as $k => $day)
+        @foreach($days[$k] as $mIndex => $m)
+        <tr>
+            @if($mIndex === 0)
+                <td rowspan="{{count($days[$k])}}">
+                    {{$k}}
+                </td>
+            @endif
+            <td>{{$m->time}}</td>
+            <td>
+                @if($m->label === 'BP')
+                    BP
+                @elseif($m->label === 'Wt. (lbs.)')
+                    Weight
+                @endif
+            </td>
+            <td>
+                @if($m->label === 'BP')
+                    {{ $m->sbp_mm_hg }}/{{ $m->dbp_mm_hg }}
+                @elseif($m->label === 'Wt. (lbs.)')
+                    {{ round(floatval($m->numeric_value), 2) }} lbs
+                @endif
+            </td>
+            <td>
+                @if($performerRole === 'MCP')
+                    <div class="width-100px">
+                        @if($m->has_been_stamped_by_mcp)
+                            <span class="text-secondary text-sm">
+                                <i class="fa fa-check"></i>
+                                Stamped
+                            </span>
+                        @else
+                            <div moe relative>
+                                <a href="#" start show>Stamp</a>
+                                <form url="/api/measurement/stampAsMcp" right class="width-300px">
+                                    <input type="hidden" name="uid" value="{{$m->measurement_uid}}">
+                                    <p class="mb-1">Stamp this measurement?</p>
+                                    <div class="mt-2 bg-light border p-2">
+                                        <div class="mb-1 text-secondary">{{ $m->label }}</div>
+                                        <div class="font-weight-bold mb-1">
+                                            @if($m->label === 'BP')
+                                                {{ round($m->sbp_mm_hg, 2) }}/{{ round($m->dbp_mm_hg, 2) }} mmHg
+                                                <span class="font-weight-normal d-inline-block pl-2">Pulse:</span>
+                                                {{ $m->value_pulse }} {{ $m->value_irregular === 0?'Irregular':'' }} {{ $m->value_irregular === 1?'Regular':'' }}
+                                            @elseif($m->label === 'Wt. (lbs.)')
+                                                {{ round($m->numeric_value, 2) }} lbs
+                                            @else
+                                                {{ $m->value }}
+                                            @endif
+                                        </div>
+                                        <div class="text-sm">
+                                            {{ $m->date }} {{ $m->time }} EST
+                                        </div>
+                                    </div>
+                                    <div class="mb-2 border border-info p-2 mt-2 bg-light">
+                                        <span>I have had interactive communication with <b>{{$patient->displayName()}}</b> during this care month.</span>
+                                        <div class="d-flex border-top mt-2">
+                                            <label class="mt-2 mb-0 d-inline-flex align-items-center mr-3">
+                                                <input type="radio" class="mr-2" name="communicatedToPatient" value="true" required>
+                                                <span>Yes</span>
+                                            </label>
+                                            <label class="mt-2 mb-0 d-inline-flex align-items-center">
+                                                <input type="radio" class="mr-2" name="communicatedToPatient" value="false" checked required>
+                                                <span>No</span>
+                                            </label>
+                                        </div>
+                                    </div>
+                                    <div class="mb-2">
+                                        <label class="mb-1 text-secondary text-sm">Memo</label>
+                                        <textarea class="form-control form-control-sm" name="memo"></textarea>
+                                    </div>
+                                    <div class="form-group m-0">
+                                        <button submit class="btn btn-primary btn-sm mr-2">Submit</button>
+                                        <button cancel class="btn btn-default border btn-sm mr-2">Cancel</button>
+                                    </div>
+                                </form>
+                            </div>
+                        @endif
+                    </div>
+                @elseif($performerRole === 'NON-MCP')
+                    <div class="width-100px">
+                        @if($m->has_been_stamped_by_non_hcp)
+                            <span class="text-secondary text-sm">
+                                <i class="fa fa-check"></i>
+                                Stamped
+                            </span>
+                        @endif
+                    </div>
+                @endif
+            </td>
+            @if($mIndex === 0)
+                <td rowspan="{{count($days[$k])}}">
+                    @if($performerRole === 'ADMIN')
+                        <div class="my-1">
+                            <span class="text-secondary">MCP Unstamped:</span>
+                            <b class="{{count($unstampedMCP[$k]) ? '' : 'text-secondary font-weight-normal'}}">{{count($unstampedMCP[$k])}}</b>
+                        </div>
+                        <div class="">
+                            <span class="text-secondary">Non-HCP Unstamped:</span>
+                            <b class="{{count($unstampedNonHCP[$k]) ? '' : 'text-secondary font-weight-normal'}}">{{count($unstampedNonHCP[$k])}}</b>
+                        </div>
+                    @elseif($performerRole === 'MCP')
+                        @if(count($unstampedMCP[$k]))
+                            <div moe relative class="btn-stamp-all">
+                                <a href="#" start show class="">
+                                    Stamp All &amp; Create Entry
+                                </a>
+                                <form url="/api/measurement/bulkStampAsMcp">
+                                    <input type="hidden" name="measurementUids" value="{{implode('|', $unstampedMCP[$k])}}">
+                                    <p class="mb-1">Stamp all measurements?</p>
+                                    <div class="mb-2 border border-info p-2 mt-2 bg-light width-300px">
+                                        <span>I have had interactive communication with <b>{{$patient->displayName()}}</b> during this care month.</span>
+                                        <div class="d-flex border-top mt-2">
+                                            <label class="mt-2 mb-0 d-inline-flex align-items-center mr-3">
+                                                <input type="radio" class="mr-2" name="communicatedToPatient" value="true" required>
+                                                <span>Yes</span>
+                                            </label>
+                                            <label class="mt-2 mb-0 d-inline-flex align-items-center">
+                                                <input type="radio" class="mr-2" name="communicatedToPatient" value="false" checked required>
+                                                <span>No</span>
+                                            </label>
+                                        </div>
+                                    </div>
+                                    <div class="mb-2">
+                                        <label class="mb-1 text-secondary text-sm">Memo</label>
+                                        <textarea class="form-control form-control-sm" name="memo"></textarea>
+                                    </div>
+                                    <div class="mb-2">
+                                        <label class="mb-1 text-secondary text-sm">Minutes</label>
+                                        <input type="number" min="1" max="15" class="form-control form-control-sm w-100" name="entryMinutes"
+                                               value="2" placeholder="Time (mins.)" required>
+                                    </div>
+                                    <div class="form-group m-0">
+                                        <button submit class="btn btn-primary btn-sm mr-2">Submit</button>
+                                        <button cancel class="btn btn-default border btn-sm mr-2">Cancel</button>
+                                    </div>
+                                </form>
+                            </div>
+                        @else
+                            <span class="text-secondary text-sm d-flex align-items-center">
+                                <i class="fa fa-check mr-2"></i>
+                                <span>All Stamped</span>
+                            </span>
+                        @endif
+                    @elseif($performerRole === 'NON-MCP')
+                    @endif
+                </td>
+                <td rowspan="{{count($days[$k])}}">
+                    @foreach($m->entries as $entry)
+                        <div class="my-1 d-flex align-items-start flex-nowrap">
+                            <b class="mr-2">{{round($entry->time_in_seconds / 60)}}m</b>
+                            <span class="text-secondary mr-2 text-nowrap text-sm">({{date('h:i a', strtotime($entry->created_at))}})</span>
+                            <span class="text-secondary inline-html-container flex-grow-1">{!! $entry->content_text !!}</span>
+                        </div>
+                    @endforeach
+                    @if($performerRole === 'MCP' || $performerRole === 'NON-HCP')
+                        <div moe large>
+                            <a start show class="py-0 mb-3 text-sm">+ Add</a>
+                            <form url="/api/careMonthEntry/createForRm">
+                                <input type="hidden" name="careMonthUid" value="{{ $careMonth->uid }}">
+                                <div class="mb-2">
+                                    <div class="row">
+                                        <div class="col-4 pr-0">
+                                            <select class="form-control form-control-sm w-100" name="proUid" provider-search data-pro-uid="{{ @$pro->uid }}"
+                                                    required>
+                                                <option value="">-- Select Pro --</option>
+                                            </select>
+                                        </div>
+                                        <div class="col-4 pr-0">
+                                            <?php
+                                            $sD = strtotime($careMonth->start_date);
+                                            $y = date('Y', $sD);
+                                            $m0 = date('m', $sD);
+                                            $d = date('t', $sD);
+                                            $yCurrent = date('Y');
+                                            $mCurrent = date('m');
+                                            ?>
+                                            <input autofocus type="date" min="{{ date($y . '-' . $m0 . '-01') }}" max="{{ date($y . '-' . $m0 . '-' . $d) }}"
+                                                   value="{{$m->dateYMD}}"
+                                                   class="form-control form-control-sm w-100" name="effectiveDate"
+                                                   placeholder="Effective Date" required>
+                                        </div>
+                                        <div class="col-4">
+                                            <input type="number" min="0" max="15" class="form-control form-control-sm w-100 cm-time-value" name="timeInMinutes"
+                                                   value="2" placeholder="Time (mins.)" required>
+                                        </div>
+                                    </div>
+                                </div>
+                                <div class="mb-2">
+                                    <div class="row">
+                                        <div class="col-12">
+                                            <div cm-rte data-content="Reviewed/managed patient measurements" data-name="contentText"></div>
+                                        </div>
+                                    </div>
+                                </div>
+                                <div class="d-flex align-items-center">
+                                    <button class="btn btn-sm btn-primary mr-2" submit>Save</button>
+                                    <button class="btn btn-sm btn-default mr-2 border" cancel>Cancel</button>
+                                </div>
+                            </form>
+                        </div>
+                    @endif
+                </td>
+            @endif
+        </tr>
+        @endforeach
+    @endforeach
+    </tbody>
+</table>
+<div class="my-3 border p-3 d-none cm-tab" tab-key="bmi-summary">
+    @include('app.patient.vitals-settings.bmi-management-summary')
+</div>
+<div class="my-3 border p-3 d-none cm-tab" tab-key="bp-summary">
+    @include('app.patient.vitals-settings.bp-management-summary')
+</div>
+</div>
+<script>
+    (function() {
+        function init() {
+            $('a[tab-link]')
+                .off('click')
+                .on('click', function () {
+                    let tab = $(this).attr('tab-link');
+                    $(this).siblings().removeClass('font-weight-bold');
+                    $(this).addClass('font-weight-bold');
+                    $('.cm-tab').addClass('d-none');
+                    $('.cm-tab[tab-key="' + tab + '"]').removeClass('d-none');
+                    return false;
+                });
+        }
+        addMCInitializer('cm-matrix-{{$patient->id}}', init, '#cm-matrix-{{$patient->id}}');
+    }).call(window);
+</script>

+ 218 - 12
resources/views/app/patient/care-month/dashboard.blade.php

@@ -20,6 +20,8 @@
             "value" => $shortcut->text
         ];
     }
+
+    $calendarID = rand(10000, 99999);
     ?>
     <script>window.userShortcuts = <?= json_encode($shortCutsObject); ?>;</script>
 
@@ -343,7 +345,7 @@
                     </div>
                     <div class="row mb-3 d-none">
                         <div class="col-9">
-                            <div id="caremonth-measurements-calendar">
+                            <div id="caremonth-measurements-calendar-{{$calendarID}}" class="caremonth-measurements-calendar">
 
                             </div>
                         </div>
@@ -364,14 +366,36 @@
                                     Need <b>{{16 - $careMonth->number_of_days_with_remote_measurements}} more days</b> with measurements before RM becomes billable.
                                 </div>
                             @endif
+
+                            <div>
+                                {{-- rm reasons --}}
+                                <div class="mb-2">
+                                    @include('app/patient/care-month/rm-reasons')
+                                </div>
+                            </div>
+
+                            <div class="mb-2">
+                                @if($careMonth->rmBill && $careMonth->rmBill->code != 'RMB')
+                                    @if(true && 'TODO Check if MCP and echo as needed for rme/rmm')
+
+                                    @endif
+                                    @if($performer->pro->id == $careMonth->mcp_pro_id)
+                                        Reimbursement: {{ $careMonth->rmBill->hcp_payment_amount }}
+                                    @endif 
+                                @endif
+                            </div>
                         </div>
                     </div>
-                    <table class="table table-striped table-sm table-bordered mt-2 mb-0">
+
+                    @include('app.patient.care-month._matrix')
+
+                    <table class="table table-striped table-sm table-bordered mt-2 mb-0 d-none">
                         <thead>
                         <tr>
                             <th class="px-2 text-secondary">Effective Date</th>
                             <th class="px-2 text-secondary w-25">Category</th>
                             <th class="px-2 text-secondary w-25">Value</th>
+                            <th class="px-2 text-secondary">Stamp</th>
                         </tr>
                         </thead>
                         <tbody>
@@ -403,6 +427,68 @@
                                             {{ $measurement->value }}
                                         @endif
                                     </td>
+                                    <td colspan="px-2">
+                                        <?php
+                                        $stampEndPoint = '';
+                                        if ($measurement->client->mcp_pro_id === $pro->id) {
+                                            $stampEndPoint = '/api/measurement/stampAsMcp';
+                                        } elseif ($measurement->client->default_na_pro_id === $pro->id || $measurement->client->rmm_pro_id === $pro->id || $measurement->client->rme_pro_id === $pro->id) {
+                                            $stampEndPoint = '/api/measurement/stampAsNonHcp';
+                                        }
+                                        ?>
+                                        @if(!empty($stampEndPoint))
+                                            <div moe relative>
+                                                <a href="#" start show>Stamp</a>
+                                                <form url="{{$stampEndPoint}}" right class="width-300px">
+                                            <input type="hidden" name="uid" value="{{$measurement->uid}}">
+                                            <p class="mb-1">Stamp this measurement?</p>
+                                            <div class="mt-2 bg-light border p-2">
+                                                <div class="mb-1 text-secondary">{{ $measurement->label }}</div>
+                                                <div class="font-weight-bold mb-1">
+                                                    @if($measurement->label === 'BP')
+                                                        {{ round($measurement->sbp_mm_hg, 2) }}/{{ round($measurement->dbp_mm_hg, 2) }} mmHg
+                                                        <span class="font-weight-normal d-inline-block pl-2">Pulse:</span>
+                                                        {{ $measurement->value_pulse }} {{ $measurement->value_irregular === 0?'Irregular':'' }} {{ $measurement->value_irregular === 1?'Regular':'' }}
+                                                    @elseif($measurement->label === 'Wt. (lbs.)')
+                                                        {{ round($measurement->numeric_value, 2) }} lbs
+                                                    @else
+                                                        {{ $measurement->value }}
+                                                    @endif
+                                                </div>
+                                                <div class="text-sm">
+                                                    <?php $timestampInSec = floor($measurement->ts / 1000); ?>
+                                                    {{ friendly_date_time_short_with_tz_from_timestamp($timestampInSec, 'EASTERN') }} EST
+                                                </div>
+                                            </div>
+                                            @if($measurement->mcp_pro_id !== $pro->id)
+                                                <div class="mb-2 border border-info p-2 mt-2 bg-light">
+                                                    <span>I have had interactive communication with {{$measurement->name_first}} {{$measurement->name_last}} during this care month.</span>
+                                                    <div class="d-flex border-top mt-2">
+                                                        <label class="mt-2 mb-0 d-inline-flex align-items-center mr-3">
+                                                            <input type="radio" class="mr-2" name="communicatedToPatient" value="true">
+                                                            <span>Yes</span>
+                                                        </label>
+                                                        <label class="mt-2 mb-0 d-inline-flex align-items-center">
+                                                            <input type="radio" class="mr-2" name="communicatedToPatient" value="false" checked>
+                                                            <span>No</span>
+                                                        </label>
+                                                    </div>
+                                                </div>
+                                            @else
+                                                <input type="hidden" name="communicatedToPatient" value="false">
+                                            @endif
+                                            <div class="mb-2">
+                                                <label class="mb-1 text-secondary text-sm">Memo</label>
+                                                <textarea class="form-control form-control-sm" name="memo"></textarea>
+                                            </div>
+                                            <div class="form-group m-0">
+                                                <button submit class="btn btn-primary btn-sm mr-2">Submit</button>
+                                                <button cancel class="btn btn-default border btn-sm mr-2">Cancel</button>
+                                            </div>
+                                        </form>
+                                            </div>
+                                        @endif
+                                    </td>
                                 </tr>
 
                                 <?php
@@ -513,17 +599,85 @@
         </div> --}}
 
         <hr class="m-negator mt-4 mb-3">
+        <div class="screen-only">
+            <div class="d-flex align-items-center mb-3">
+                <p class="font-weight-bold text-secondary m-0 font-size-14">RM Setup</p>
+            </div>
 
-        {{-- rm reasons --}}
-        <div class="mb-2">
-            @include('app/patient/care-month/rm-reasons')
-        </div>
+            <div class="mb-3 d-flex align-items-center">
+                <span class="min-width-140px">RM Setup Status:</span>
+                <div class="d-inline-flex align-items-center flex-grow-1">
+                    @if($patient->has_rm_setup_been_performed)
+                        <span class="text-nowrap text-success">
+                            <i class="fa fa-check"></i>
+                            <b>Enrolled</b>
+                        </span>
+                        <div moe class="ml-3">
+                            <a href="" show start>Undo</a>
+                            <form url="/api/careMonth/undoMarkRmSetupPerformed">
+                                <input type="hidden" name="uid" value="{{$careMonth->uid}}">
+                                <p>Un-enroll from RM?</p>
+                                <div class="mb-0">
+                                    <button class="btn btn-primary btn-sm" submit>Submit</button>
+                                    <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                                </div>
+                            </form>
+                        </div>
+                    @else
+                        <span class="text-nowrap text-warning-mellow">
+                            <i class="fa fa-times"></i>
+                            <b>Not Enrolled</b>
+                        </span>
+                        <div moe class="ml-3">
+                            <a href="" show start>Mark as enrolled</a>
+                            <form url="/api/careMonth/markRmSetupPerformed">
+                                <input type="hidden" name="uid" value="{{$careMonth->uid}}">
+                                <p>Mark as enrolled into RM?</p>
+                                <div class="mb-0">
+                                    <button class="btn btn-primary btn-sm" submit>Submit</button>
+                                    <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                                </div>
+                            </form>
+                        </div>
+                    @endif
+                </div>
+            </div>
 
-        <hr class="m-negator mt-0 mb-3">
+            @if($pro->pro_type === 'ADMIN')
+                <div class="d-flex align-items-center">
+                    <span class="min-width-140px">RM Setup Claim:</span>
+                    <div class="d-inline-flex align-items-center flex-grow-1">
+                        @if(!!$careMonth->rmSetupClaim)
+                            <span class="text-nowrap text-success">
+                                <i class="fa fa-check"></i>
+                                <b>Created</b>
+                            </span>
+                        @else
+                            <span class="text-nowrap text-warning-mellow">
+                                <i class="fa fa-times"></i>
+                                <b>Not Created</b>
+                            </span>
+                            <div moe class="ml-3">
+                                <a href="" show start>Generate</a>
+                                <form url="/api/careMonth/generateRmSetupClaim">
+                                    <input type="hidden" name="uid" value="{{$careMonth->uid}}">
+                                    <p>Generate RM setup claim?</p>
+                                    <div class="mb-0">
+                                        <button class="btn btn-primary btn-sm" submit>Submit</button>
+                                        <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                                    </div>
+                                </form>
+                            </div>
+                        @endif
+                    </div>
+                </div>
+            @endif
 
-        <hr class="m-negator mt-0 mb-3">
+        </div>
 
         @if($pro->pro_type === 'ADMIN')
+
+            <hr class="m-negator my-3">
             <div class="pb-3 screen-only">
                 <div class="ml-auto d-flex align-items-center">
 
@@ -1243,7 +1397,7 @@
 
 
             {{-- bills --}}
-            @if(($pro->pro_type === 'ADMIN' || ($careMonth->mcp && $pro->id === $careMonth->mcp->id) ) && false)
+            @if($pro->pro_type === 'ADMIN' || ($careMonth->mcp && $pro->id === $careMonth->mcp->id && false))
                 @if($careMonth->bills->count())
                     <div class="">
                         <div class="d-flex align-items-center mb-2">
@@ -1678,7 +1832,7 @@
                 @endif
             @endif
 
-
+                                                     
             <hr class="m-negator mt-4 mb-3">
 
             {{-- claims --}}
@@ -2051,6 +2205,58 @@
             @endif
 
         @endif
+        <hr class="m-negator mt-4 mb-3">
+            <div>
+                Is RM interaction waived: {{$careMonth->is_rm_interaction_waived? 'Yes': 'No'}}
+                <div moe class="text-left mt-1" title="Cancel Claim">
+                    <a class="" href="" show start>Set Is RM Interaction Waived To False</a>
+                    @if($careMonth->is_rm_interaction_waived)
+                    <form url="/api/careMonth/setIsRmInteractionWaivedToFalse">
+                        <input type="hidden" name="uid" value="{{$careMonth->uid}}">
+                        <p>Set is RM interaction waived to false?</p>
+                        <div class="mb-0">
+                            <button class="btn btn-primary btn-sm" submit>Submit</button>
+                            <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                        </div>
+                    </form>
+                    @else 
+                        <form url="/api/careMonth/setIsRmInteractionWaivedToTrue">
+                            <input type="hidden" name="uid" value="{{$careMonth->uid}}">
+                            <p>Set is RM interaction waived to true?</p>
+                            <div class="mb-0">
+                                <button class="btn btn-primary btn-sm" submit>Submit</button>
+                                <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                            </div>
+                        </form>                                    
+                    @endif 
+                </div>
+            </div>                                   
+                 
+            <div>
+                Is RM interaction waived: {{$careMonth->is_rm_time_waived? 'Yes': 'No'}}
+                <div moe class="text-left mt-1" title="Cancel Claim">
+                    <a class="" href="" show start>Set Is RM Time Waived To False</a>
+                    @if($careMonth->is_rm_time_waived)
+                    <form url="/api/careMonth/setIsRmTimeWaivedToFalse">
+                        <input type="hidden" name="uid" value="{{$careMonth->uid}}">
+                        <p>Set is RM Time waived to false?</p>
+                        <div class="mb-0">
+                            <button class="btn btn-primary btn-sm" submit>Submit</button>
+                            <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                        </div>
+                    </form>
+                    @else 
+                        <form url="/api/careMonth/setIsRmTimeWaivedToTrue">
+                            <input type="hidden" name="uid" value="{{$careMonth->uid}}">
+                            <p>Set is RM time waived to true?</p>
+                            <div class="mb-0">
+                                <button class="btn btn-primary btn-sm" submit>Submit</button>
+                                <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                            </div>
+                        </form>                                    
+                    @endif 
+                </div>
+            </div>  
 
         <hr class="m-negator my-3">
 
@@ -2108,8 +2314,8 @@
 
                 // init calendar view
                 @if(count($plottableMeasurements))
-                $('#caremonth-measurements-calendar').closest('.d-none').removeClass('d-none');
-                let measurementsCalendar = new FullCalendar.Calendar($('#caremonth-measurements-calendar')[0], {
+                $('#caremonth-measurements-calendar-{{$calendarID}}').closest('.d-none').removeClass('d-none');
+                let measurementsCalendar = new FullCalendar.Calendar($('#caremonth-measurements-calendar-{{$calendarID}}')[0], {
                     headerToolbar: false,
                     initialView: 'dayGridMonth',
                     initialDate: '{{ date('Y-m-d', strtotime($careMonth->created_at)) }}',

+ 5 - 0
resources/views/app/patient/care-month/matrix.blade.php

@@ -0,0 +1,5 @@
+@extends ('layouts.patient')
+
+@section('inner-content')
+    @include('app.patient.care-month._matrix')
+@endsection

+ 10 - 0
resources/views/app/patient/care-months.blade.php

@@ -112,6 +112,7 @@
                 <th class="px-2 text-secondary border-bottom-0">MCP</th>
                 <th class="px-2 text-secondary border-bottom-0">RMM</th>
                 <th class="px-2 text-secondary border-bottom-0">RME</th>
+                <th class="px-2 text-secondary border-bottom-0">Matrix</th>
             </tr>
             </thead>
             <tbody>
@@ -133,6 +134,15 @@
                     <td class="px-2">{{$careMonth->mcp ? $careMonth->mcp->name_display : '-'}}</td>
                     <td class="px-2">{{$careMonth->rmmPro ? $careMonth->rmmPro->name_display : '-'}}</td>
                     <td class="px-2">{{$careMonth->rmePro ? $careMonth->rmePro->name_display : '-'}}</td>
+                    <td class="px-2">
+                        <a native target="_blank"
+                           open-in-stag-popup
+                           mc-initer="cm-matrix-{{$patient->id}}"
+                           title="Care Month Matrix: {{date('M Y', strtotime($careMonth->start_date))}}"
+                           href="/patient-care-month-matrix/{{$careMonth->uid}}">
+                            View
+                        </a>
+                    </td>
                 </tr>
             @endforeach
             </tbody>

+ 3 - 2
resources/views/app/patient/claims-resolver.blade.php

@@ -53,6 +53,7 @@
         if($note->is_claim_closed) $totalNotesWithClaimingClosed++;
     }
     ?>
+    <div id="claims-resolver">
     <h2><strong>Numbers:</strong></h2>
     <table class="table table-sm table-striped">
         <tr>
@@ -413,7 +414,7 @@
         </tbody>
     </table>
     </div>
-
+    </div>
     <script>
         (function() {
             function init() {
@@ -423,7 +424,7 @@
                     scrollX: true
                 });
             }
-            addMCInitializer('claims-resolver', init);
+            addMCInitializer('claims-resolver', init, '#claims-resolver');
         }).call(window);
     </script>
 

+ 875 - 0
resources/views/app/patient/client-primary-coverages.blade.php

@@ -0,0 +1,875 @@
+@extends ('layouts.patient')
+
+@section('inner-content')
+<div>
+    <div class="mb-3 border rounded bg-light p-2">
+        <div class="mb-2">
+            Latest Client Primary Coverage: 
+            @if($patient->latestClientPrimaryCoverage)
+                <b>{{$patient->latestClientPrimaryCoverage->plan_type}}</b> (Member ID: {{$patient->latestClientPrimaryCoverage->payer_member_identifier}})
+            @else 
+                -
+            @endif
+        </div>
+        <div class="mb-2">Latest New Client Primary Coverage:
+            @if($patient->latestNewClientPrimaryCoverage)
+                <b>{{$patient->latestNewClientPrimaryCoverage->plan_type}}</b> (Member ID: {{$patient->latestNewClientPrimaryCoverage->payer_member_identifier}})
+            @else 
+                -
+            @endif
+        </div>
+        <div class="mb-2">Latest Auto Refresh Client Primary Coverage:
+            @if($patient->latestAutoRefreshClientPrimaryCoverage)
+                <b>{{$patient->latestAutoRefreshClientPrimaryCoverage->plan_type}}</b> (Member ID: {{$patient->latestAutoRefreshClientPrimaryCoverage->payer_member_identifier}})
+            @else 
+                -
+            @endif
+        </div>
+        <div class="">Latest Manual Client Primary Coverage:
+            @if($patient->latestManualClientPrimaryCoverage)
+                <b>{{$patient->latestManualClientPrimaryCoverage->plan_type}}</b> (Member ID: {{$patient->latestManualClientPrimaryCoverage->payer_member_identifier}})
+            @else 
+                -
+            @endif
+        </div>
+    </div>
+    <div class="d-flex align-items-baseline">
+        <h4 class="font-weight-bold m-0 font-size-16 text-nowrap">Client Primary Coverages</h4>
+        <div class="ml-auto d-inline-flex justify-content-center">
+            <span class="mr-2">New w/o Manual:</span>
+            <div moe relative large>
+                <a href="" start show>+ MC</a>
+                <form url="/api/clientPrimaryCoverage/createNewCoverageForMedicareWithoutManualDetermination" right class="mcp-theme-1">
+                    <input type="hidden" name="clientUid" value="{{$patient->uid}}" class="form-control input-sm" />
+                    <div class="form-group">
+                        <label class="control-label">Subscriber Name First</label>
+                        <input type="text" name="subscriberNameFirst" class="form-control input-sm" value="{{$patient->name_first}}" />
+                    </div>
+                    <div class="form-group">
+                        <label class="control-label">Subscriber Name Last</label>
+                        <input type="text" name="subscriberNameLast" class="form-control input-sm" value="{{$patient->name_last}}" />
+                    </div>
+                    <div class="form-group">
+                        <label class="control-label">Subscriber Dob</label>
+                        <input type="date" name="subscriberDob" class="form-control input-sm" value="{{$patient->dob}}" />
+                    </div>
+                    <div class="form-group">
+                        <label class="control-label">Payer Member Identifier</label>
+                        <input type="text" name="payerMemberIdentifier" class="form-control input-sm" />
+                    </div>
+                    <div class="form-group">
+                        <label class="control-label">Date Of Service</label>
+                        <input type="date" name="dateOfService" class="form-control input-sm" value="{{date('Y-m-d')}}" />
+                    </div>
+                    <div class="form-group text-nowrap mb-0">
+                        <button class="btn btn-sm btn-primary" submit>Submt</button>
+                        <button class="btn btn-sm btn-default border" close>Close</button>
+                    </div>
+                </form>
+            </div>
+            <span class="mx-2 text-secondary text-sm">|</span>
+            <div moe relative large>
+                <a href="" start show >+ Medicaid</a>
+                <form url="/api/clientPrimaryCoverage/createNewCoverageForMedicaidWithoutManualDetermination" right class="mcp-theme-1">
+                    <input type="hidden" name="clientUid" value="{{$patient->uid}}" class="form-control input-sm" />
+                    <div class="form-group">
+                        <label for="" class="control-label">Subscriber Name First</label>
+                        <input type="text" name="subscriberNameFirst" class="form-control input-sm" value="{{$patient->name_first}}">
+                    </div>
+                    <div class="form-group">
+                        <label for="" class="control-label">Subscriber Name Last</label>
+                        <input type="text" name="subscriberNameLast" class="form-control input-sm" value="{{$patient->name_last}}">
+                    </div>
+                    <div class="form-group">
+                        <label for="" class="control-label">Subscriber Dob</label>
+                        <input type="date" name="subscriberDob" class="form-control input-sm" value="{{$patient->dob}}">
+                    </div>
+                    <div class="form-group">
+                        <label for="" class="control-label">Subscriber Sex</label>
+                        <select  name="subscriberSex" class="form-control input-sm">
+                            <option value="">--select--</option>
+                            <option value="M" {{$patient->sex === 'M' ? 'selected' : ''}}>M</option>
+                            <option value="F" {{$patient->sex === 'F' ? 'selected' : ''}}>F</option>
+                        </select>
+                    </div>
+                    <div class="form-group">
+                        <label for="" class="control-label">Payer Name</label>
+                        <input type="text" name="payerName" class="form-control input-sm">
+                    </div>
+                    <div class="form-group">
+                        <label for="" class="control-label">Payer Member Identifier</label>
+                        <input type="String" name="payerMemberIdentifier" class="form-control input-sm">
+                    </div>
+                    <div class="form-group">
+                        <label for="" class="control-label">Date Of Service</label>
+                        <input type="date" name="dateOfService" class="form-control input-sm" value="{{date('Y-m-d')}}">
+                    </div>
+                   
+                    <div class="form-group text-nowrap mb-0">
+                        <button class="btn btn-sm btn-primary" submit>Submt</button>
+                        <button class="btn btn-sm btn-default border" close>Close</button>
+                    </div>
+                </form>
+            </div>
+            <span class="mx-2 text-secondary text-sm">|</span>
+            <div moe relative large>
+                <a href="" start show >+ Comm.</a>
+                <form url="/api/clientPrimaryCoverage/createNewCoverageForCommercialWithoutManualDetermination" right class="mcp-theme-1">
+                    <input type="hidden" name="clientUid" value="{{$patient->uid}}" class="form-control input-sm" />
+                    <div class="form-group">
+                        <label class="control-label">Subscriber Name First</label>
+                        <input type="text" name="subscriberNameFirst" class="form-control input-sm" value="{{$patient->name_first}}">
+                    </div>
+                    <div class="form-group">
+                        <label class="control-label">Subscriber Name Last</label>
+                        <input type="text" name="subscriberNameLast" class="form-control input-sm" value="{{$patient->name_last}}">
+                    </div>
+                    <div class="form-group">
+                        <label class="control-label">Subscriber Dob</label>
+                        <input type="date" name="subscriberDob" class="form-control input-sm" value="{{$patient->dob}}">
+                    </div>
+                    <div class="form-group">
+                        <label for="" class="control-label">Subscriber Sex</label>
+                        <select  name="subscriberSex" class="form-control input-sm">
+                            <option value="">--select--</option>
+                            <option value="M" {{$patient->sex === 'M' ? 'selected' : ''}}>M</option>
+                            <option value="F" {{$patient->sex === 'F' ? 'selected' : ''}}>F</option>
+                        </select>
+                    </div>
+                    <div class="form-group">
+                        <label class="control-label">Payer Name</label>
+                        <input type="text" name="payerName" class="form-control input-sm">
+                    </div>
+                    <div class="form-group">
+                        <label class="control-label">Payer Member Identifier</label>
+                        <input type="text" name="payerMemberIdentifier" class="form-control input-sm">
+                    </div>
+                    <div class="form-group">
+                        <label class="control-label">Date Of Service</label>
+                        <input type="date" name="dateOfService" class="form-control input-sm" value="{{date('Y-m-d')}}">
+                    </div>
+                    
+                    <div class="form-group text-nowrap mb-0">
+                        <button class="btn btn-sm btn-primary" submit>Submt</button>
+                        <button class="btn btn-sm btn-default border" close>Close</button>
+                    </div>
+                </form>
+            </div>
+        </div>
+        <div class="ml-4 d-inline-flex justify-content-center">
+            <span class="mr-2">New w/ Manual:</span>
+            <div moe relative large>
+                <a href="" start show >+ MC</a>
+                <form url="/api/clientPrimaryCoverage/createNewCoverageForMedicareWithManualDetermination" right class="mcp-theme-1">
+                    <input type="hidden" name="clientUid" value="{{$patient->uid}}" class="form-control input-sm" />
+                    <div class="form-group">
+                        <label for="" class="control-label">Subscriber Name First</label>
+                        <input type="text" name="subscriberNameFirst" class="form-control input-sm" value="{{$patient->name_first}}"/>
+                    </div>
+                    <div class="form-group">
+                        <label for="" class="control-label">Subscriber Name Last</label>
+                        <input type="text" name="subscriberNameLast" class="form-control input-sm" value="{{$patient->name_last}}"/>
+                    </div>
+                    <div class="form-group">
+                        <label for="" class="control-label">Subscriber Dob</label>
+                        <input type="date" name="subscriberDob" class="form-control input-sm" value="{{$patient->dob}}"/>
+                    </div>
+                    <div class="form-group">
+                        <label for="" class="control-label">Payer Member Identifier</label>
+                        <input type="text" name="payerMemberIdentifier" class="form-control input-sm"/>
+                    </div>
+                    <div class="form-group">
+                        <label for="" class="control-label">Date Of Service</label>
+                        <input type="date" name="dateOfService" class="form-control input-sm" value="{{date('Y-m-d')}}"/>
+                    </div>
+                    <div class="form-group">
+                        <label for="" class="control-label">Manual Determination Strategy</label>
+                        <select  name="manualDeterminationStrategy" class="form-control input-sm">
+                            <option value="">--select--</option>
+                            <option value="REVIEWED_ELECTRONIC">Reviewed electronic</option>
+                            <option value="CALLED_PAYER">Called payer</option>
+                        </select>
+                    </div>
+                    <div class="form-group">
+                        <label for="" class="control-label">Manual Determination Category</label>
+                        <select  name="manualDeterminationCategory" class="form-control input-sm">
+                            <option value="">--select--</option>
+                            <option value="COVERED">Covered</option>
+                            <option value="NOT_COVERED">Not Covered</option>
+                            <option value="INVALID">Invalid</option>
+                            <option value="UNKNOWN">Unknown</option>
+                        </select>                        
+                    </div>
+                    <div class="form-group">
+                        <label for="" class="control-label">Manual Determination Category Memo</label>
+                        <input type="text" name="manualDeterminationCategoryMemo" class="form-control input-sm"/>
+                    </div>
+                    <div class="form-group">
+                        <label for="" class="control-label">Manual Detail Json</label>
+                        <input type="text" name="manualDetailJson" class="form-control input-sm"/>
+                    </div>
+                    <div class="form-group">
+                        <label for="" class="control-label">Manual Medicare Is Part B Primary</label>
+                        <select  name="manualMedicareIsPartBPrimary" class="form-control input-sm">
+                            <option value="">--select--</option>
+                            <option value="YES">Yes</option>
+                            <option value="NO">No</option>
+                            <option value="UNKNOWN">Unknown</option>
+                        </select>
+                    </div>
+                    <div class="form-group">
+                        <label for="" class="control-label">Manual Medicare Is Part B Active</label>
+                        <select  name="manualMedicareIsPartBActive" class="form-control input-sm">
+                            <option value="">--select--</option>
+                            <option value="YES">Yes</option>
+                            <option value="NO">No</option>
+                            <option value="UNKNOWN">Unknown</option>
+                        </select>
+                    </div>
+                    <div class="form-group">
+                        <label for="" class="control-label">Manual Medicare Is Part C Active</label>
+                        <select  name="manualMedicareIsPartCActive" class="form-control input-sm">
+                            <option value="">--select--</option>
+                            <option value="YES">Yes</option>
+                            <option value="NO">No</option>
+                            <option value="UNKNOWN">Unknown</option>
+                        </select>
+                    </div>
+                    <div class="form-group">
+                        <label for="" class="control-label">Manual Medicare Is Inpatient</label>
+                        <select  name="manualMedicareIsInpatient" class="form-control input-sm">
+                            <option value="">--select--</option>
+                            <option value="YES">Yes</option>
+                            <option value="NO">No</option>
+                            <option value="UNKNOWN">Unknown</option>
+                        </select>
+                    </div>
+                    <div class="form-group">
+                        <label for="" class="control-label">Manual Medicare Is Hospice Or Home Health</label>
+                        <select  name="manualMedicareIsHospiceOrHomeHealth" class="form-control input-sm">
+                            <option value="">--select--</option>
+                            <option value="YES">Yes</option>
+                            <option value="NO">No</option>
+                            <option value="UNKNOWN">Unknown</option>
+                        </select>
+                    </div>
+                    <div class="form-group">
+                        <label for="" class="control-label">Manual Medicare Is Msp</label>
+                        <select  name="manualMedicareIsMsp" class="form-control input-sm">
+                            <option value="">--select--</option>
+                            <option value="YES">Yes</option>
+                            <option value="NO">No</option>
+                            <option value="UNKNOWN">Unknown</option>
+                        </select>
+                    </div>
+                    <div class="form-group">
+                        <label for="" class="control-label">Manual Medicare Msp Memo</label>
+                        <select  name="manualMedicareMspMemo" class="form-control input-sm">
+                            <option value="">--select--</option>
+                            <option value="YES">Yes</option>
+                            <option value="NO">No</option>
+                            <option value="UNKNOWN">Unknown</option>
+                        </select>
+                    </div>
+                    <div class="form-group">
+                        <label for="" class="control-label">Manual Medicare Mpb Start Date</label>
+                        <input type="date" name="manualMedicareMpbStartDate" class="form-control input-sm"/>
+                    </div>
+                    <div class="form-group">
+                        <label for="" class="control-label">Manual Medicare Mpb End Date</label>
+                        <input type="date" name="manualMedicareMpbEndDate" class="form-control input-sm"/>
+                    </div>
+                    <div class="form-group">
+                        <label for="" class="control-label">Manual Medicare Mpb Deductible</label>
+                        <input type="number" name="manualMedicareMpbDeductible" class="form-control input-sm"/>
+                    </div>
+                    <div class="form-group">
+                        <label for="" class="control-label">Manual Medicare Mpb Remaining</label>
+                        <input type="number" name="manualMedicareMpbRemaining" class="form-control input-sm"/>
+                    </div>
+                    <div class="form-group">
+                        <label for="" class="control-label">Manual Medicare Mpb Insurance Type</label>
+                        <input type="text" name="manualMedicareMpbInsuranceType" class="form-control input-sm"/>
+                    </div>
+                    <div class="form-group">
+                        <label for="" class="control-label">Manual Medicare Mpb Insurance Type Label</label>
+                        <input type="text" name="manualMedicareMpbInsuranceTypeLabel" class="form-control input-sm"/>
+                    </div>
+                    <div class="form-group">
+                        <label for="" class="control-label">Manual Medicare Mpb Coinsurance Percent</label>
+                        <input type="number" name="manualMedicareMpbCoinsurancePercent" class="form-control input-sm"/>
+                    </div>
+                    <div class="form-group">
+                        <label for="" class="control-label">Manual Medicare Mpb Info Valid Until</label>
+                        <input type="date" name="manualMedicareMpbInfoValidUntil" class="form-control input-sm"/>
+                    </div>
+                    <div class="form-group">
+                        <label for="" class="control-label">Manual Medicare Mpb Info Valid Till</label>
+                        <input type="date" name="manualMedicareMpbInfoValidTill" class="form-control input-sm"/>
+                    </div>
+                    <div class="form-group text-nowrap mb-0">
+                        <button class="btn btn-sm btn-primary" submit>Submt</button>
+                        <button class="btn btn-sm btn-default border" close>Close</button>
+                    </div>
+                </form>
+            </div>
+            <span class="mx-2 text-secondary text-sm">|</span>
+            <div moe relative large>
+                <a href="" start show >+ Medicaid</a>
+                <form url="/api/clientPrimaryCoverage/createNewCoverageForMedicaidWithManualDetermination" right class="mcp-theme-1">
+                    <input type="hidden" name="clientUid" value="{{$patient->uid}}" class="form-control input-sm" />
+                    <div class="form-group">
+                        <label for="" class="control-label">Manual Determination Strategy</label>
+                        <select  name="manualDeterminationStrategy" class="form-control input-sm">
+                            <option value="">--select--</option>
+                            <option value="REVIEWED_ELECTRONIC">Reviewed electronic</option>
+                            <option value="CALLED_PAYER">Called payer</option>
+                        </select>
+                    </div>
+                    <div class="form-group">
+                        <label for="" class="control-label">Manual Determination Category</label>
+                        <select  name="manualDeterminationCategory" class="form-control input-sm">
+                            <option value="">--select--</option>
+                            <option value="COVERED">Covered</option>
+                            <option value="NOT_COVERED">Not Covered</option>
+                            <option value="INVALID">Invalid</option>
+                            <option value="UNKNOWN">Unknown</option>
+                        </select>                        
+                    </div>
+                    <div class="form-group">
+                        <label for="" class="form-control-label">Manual Determination Category Memo</label>
+                        <input type="text" name="manualDeterminationCategoryMemo" class="form-control input-sm">
+                    </div>
+                    <div class="form-group">
+                        <label for="" class="control-label">Manual Detail Json</label>
+                        <input type="text" name="manualDetailJson" class="form-control input-sm">
+                    </div>
+                    <div class="form-group text-nowrap mb-0">
+                        <button class="btn btn-sm btn-primary" submit>Submt</button>
+                        <button class="btn btn-sm btn-default border" close>Close</button>
+                    </div>
+                </form>
+            </div>
+            <span class="mx-2 text-secondary text-sm">|</span>
+            <div moe relative large>
+                <a href="" start show >+ Comm.</a>
+                <form url="/api/clientPrimaryCoverage/createNewCoverageForCommercialWithManualDetermination" right class="mcp-theme-1">
+                    <input type="hidden" name="clientUid" value="{{$patient->uid}}" class="form-control input-sm" />
+                    <div class="form-group">
+                        <label class="control-label">Subscriber Name First</label>
+                        <input type="text" name="subscriberNameFirst" class="form-control input-sm" value="{{$patient->name_first}}">
+                    </div>
+                    <div class="form-group">
+                        <label class="control-label">Subscriber Name Last</label>
+                        <input type="text" name="subscriberNameLast" class="form-control input-sm" value="{{$patient->name_last}}">
+                    </div>
+                    <div class="form-group">
+                        <label class="control-label">Subscriber Dob</label>
+                        <input type="date" name="subscriberDob" class="form-control input-sm" value="{{$patient->dob}}">
+                    </div>
+                    <div class="form-group">
+                        <label for="" class="control-label">Subscriber Sex</label>
+                        <select  name="subscriberSex" class="form-control input-sm">
+                            <option value="">--select--</option>
+                            <option value="M" {{$patient->sex === 'M' ? 'selected' : ''}}>M</option>
+                            <option value="F" {{$patient->sex === 'F' ? 'selected' : ''}}>F</option>
+                        </select>
+                    </div>
+                    <div class="form-group">
+                        <label for="" class="control-label">Payer Name</label>
+                        <input type="text" name="payerName" class="form-control input-sm"/>
+                    </div>
+                    <div class="form-group">
+                        <label class="control-label">Payer Member Identifier</label>
+                        <input type="text" name="payerMemberIdentifier" class="form-control input-sm">
+                    </div>
+                    <div class="form-group">
+                        <label class="control-label">Date Of Service</label>
+                        <input type="date" name="dateOfService" class="form-control input-sm" value="{{date('Y-m-d')}}">
+                    </div>
+                   
+                    <div class="form-group">
+                        <label for="" class="control-label">Manual Determination Strategy</label>
+                        <select  name="manualDeterminationStrategy" class="form-control input-sm">
+                            <option value="">--select--</option>
+                            <option value="REVIEWED_ELECTRONIC">Reviewed electronic</option>
+                            <option value="CALLED_PAYER">Called payer</option>
+                        </select>
+                    </div>
+                    <div class="form-group">
+                        <label for="" class="control-label">Manual Determination Category</label>
+                        <select  name="manualDeterminationCategory" class="form-control input-sm">
+                            <option value="">--select--</option>
+                            <option value="COVERED">Covered</option>
+                            <option value="NOT_COVERED">Not Covered</option>
+                            <option value="INVALID">Invalid</option>
+                            <option value="UNKNOWN">Unknown</option>
+                        </select>                        
+                    </div>
+                    <div class="form-group">
+                        <label for="" class="control-label">Manual Determination Category Memo</label>
+                        <textarea name="manualDeterminationCategoryMemo" class="form-control input-sm"></textarea>
+                    </div>
+                    <div class="form-group">
+                        <label for="" class="control-label">Manual Detail Json</label>
+                        <textarea name="manualDetailJson" class="form-control input-sm"></textarea>
+                    </div>
+                    <div class="form-group text-nowrap mb-0">
+                        <button class="btn btn-sm btn-primary" submit>Submt</button>
+                        <button class="btn btn-sm btn-default border" close>Close</button>
+                    </div>
+                </form>
+            </div>
+        </div>
+    </div>
+
+    <table class="table table-sm table-bordered mt-3 mb-0">
+        <thead>
+            <tr>
+                <th></th>
+                <th>Creation Strategy</th>
+                <th>Auto Refresh Of Client Primary Coverage Id</th>
+                <th>Manual Determination Of Client Primary Coverage Id</th>
+                <th>Plan Type</th>
+                <th>Is Partbprimary</th>
+                <th>Is Manually Determined</th>
+                <th>Is Entry Error</th>
+                <th>Subscriber Name First</th>
+                <th>Subscriber Name Last</th>
+                <th>Subscriber Sex</th>
+                <th>Subscriber Dob</th>
+                <th>Payer Member Identifier</th>
+                <th>Payer Name</th>
+                <th>Date Of Service</th>
+                <th>Auto Is Payer Member Identifier Valid</th>
+                <th>Auto Detail Json</th>
+                <th>Auto Medicare Is Partbprimary</th>
+                <th>Auto Medicare Is Partbactive</th>
+                <th>Auto Medicare Is Partcactive</th>
+                <th>Auto Medicare Is Inpatient</th>
+                <th>Auto Medicare Is Hospice Or Home Health</th>
+                <th>Auto Medicare Is Msp</th>
+                <th>Auto Medicare Msp Memo</th>
+                <th>Auto Medicare Mpb Start Date</th>
+                <th>Auto Medicare Mpb End Date</th>
+                <th>Auto Medicare Mpb Deductible</th>
+                <th>Auto Medicare Mpb Remaining</th>
+                <th>Auto Medicare Mpb Insurance Type</th>
+                <th>Auto Medicare Mpb Insurance Type Label</th>
+                <th>Auto Medicare Mpb Coinsurance Percent</th>
+                <th>Auto Medicare Mpb Info Valid Until</th>
+                <th>Auto Medicare Mpb Info Valid Till</th>
+                <th>Auto Medicare Mpb Last Refreshed At</th>
+                <th>Was Successful</th>
+                <th>Reject Reason Code</th>
+                <th>Reject Reason Description</th>
+                <th>Follow Up Action Code</th>
+                <th>Follow Up Action Description</th>
+                <th>Details</th>
+                <th>Is Mcn Valid Number</th>
+                <th>Address Street Line1</th>
+                <th>Address Street Line2</th>
+                <th>Address City</th>
+                <th>Address State</th>
+                <th>Address Zip</th>
+                <th>Is Hospice</th>
+                <th>Mcn Response Detail</th>
+                <th>Billing Address</th>
+                <th>Reason Not Partb</th>
+                <th>Reason Not Partbmemo</th>
+                <th>Is Medicare Advantage</th>
+                <th>Medicare Advantage Plan</th>
+                <th>Mpb Active</th>
+                <th>Mpb Start Date</th>
+                <th>Mpb End Date</th>
+                <th>Mpb Deductible</th>
+                <th>Mpb Remaining</th>
+                <th>Mpb Insurance Type</th>
+                <th>Mpb Insurance Type Label</th>
+                <th>Mpb Coinsurance Percent</th>
+                <th>Mpb Info Valid Until</th>
+                <th>Mpb Info Valid Till</th>
+                <th>Mpb Last Refreshed At</th>
+                <th>Manual Determination Strategy</th>
+                <th>Manual Determination Category</th>
+                <th>Manual Determination Category Memo</th>
+                <th>Manual Detail Json</th>
+                <th>Manual Medicare Is Partbprimary</th>
+                <th>Manual Medicare Is Partbactive</th>
+                <th>Manual Medicare Is Partcactive</th>
+                <th>Manual Medicare Is Inpatient</th>
+                <th>Manual Medicare Is Hospice Or Home Health</th>
+                <th>Manual Medicare Is Msp</th>
+                <th>Manual Medicare Msp Memo</th>
+                <th>Manual Medicare Mpb Start Date</th>
+                <th>Manual Medicare Mpb End Date</th>
+                <th>Manual Medicare Mpb Deductible</th>
+                <th>Manual Medicare Mpb Remaining</th>
+                <th>Manual Medicare Mpb Insurance Type</th>
+                <th>Manual Medicare Mpb Insurance Type Label</th>
+                <th>Manual Medicare Mpb Coinsurance Percent</th>
+                <th>Manual Medicare Mpb Info Valid Until</th>
+                <th>Manual Medicare Mpb Info Valid Till</th>
+                <th>Manual Medicare Mpb Last Refreshed At</th>
+                <th>Auto Medicare Result Id</th>
+            </tr>
+        </thead>
+        <tbody>
+            @foreach($patient->primaryCoverages as $cpc)
+            <tr>
+                <td>
+                    @if($cpc->plan_type == 'MEDICARE')
+                    <div moe relative>
+                        <a href="" start show class="">Refresh</a>
+
+                        <form url="/api/clientPrimaryCoverage/refreshCoverageForMedicare" class="mcp-theme-1">
+                            <input type="hidden" name="uid" value="{{$cpc->uid}}" class="form-control input-sm" />
+                            <div class="form-group">
+                                <p>Refresh?</p>
+                            </div>
+                            <div class="form-group text-nowrap mb-0">
+                                <button class="btn btn-sm btn-primary" submit>Submt</button>
+                                <button class="btn btn-sm btn-default border" close>Close</button>
+                            </div>
+                        </form>
+                    </div>
+
+                    <div moe relative large>
+                        <a href="" start show class="">Manual Determination</a>
+
+                        <form url="/api/clientPrimaryCoverage/manualDeterminationForMedicare" class="mcp-theme-1">
+                            <input type="hidden" name="uid" value="{{$cpc->uid}}" class="form-control input-sm" />
+                            <div class="form-group">
+                                <label for="" class="control-label">Manual Determination Strategy</label>
+                                <select  name="manualDeterminationStrategy" class="form-control input-sm">
+                                    <option value="">--select--</option>
+                                    <option value="REVIEWED_ELECTRONIC">Reviewed electronic</option>
+                                    <option value="CALLED_PAYER">Called payer</option>
+                                </select>
+                            </div>
+                            <div class="form-group">
+                                <label for="" class="control-label">Manual Determination Category</label>
+                                <select  name="manualDeterminationCategory" class="form-control input-sm">
+                                    <option value="">--select--</option>
+                                    <option value="COVERED">Covered</option>
+                                    <option value="NOT_COVERED">Not Covered</option>
+                                    <option value="INVALID">Invalid</option>
+                                    <option value="UNKNOWN">Unknown</option>
+                                </select>                        
+                            </div>
+                            <div class="form-group">
+                                <label for="" class="control-label">Manual Determination Category Memo</label>
+                                <input type="text" name="manualDeterminationCategoryMemo" class="form-control input-sm"/>
+                            </div>
+                            <div class="form-group">
+                                <label for="" class="control-label">Manual Detail Json</label>
+                                <input type="text" name="manualDetailJson" class="form-control input-sm"/>
+                            </div>
+                            <div class="form-group">
+                                <label for="" class="control-label">Manual Medicare Is Part B Primary</label>
+                                <select  name="manualMedicareIsPartBPrimary" class="form-control input-sm">
+                                    <option value="">--select--</option>
+                                    <option value="YES">Yes</option>
+                                    <option value="NO">No</option>
+                                    <option value="UNKNOWN">Unknown</option>
+                                </select>
+                            </div>
+                            <div class="form-group">
+                                <label for="" class="control-label">Manual Medicare Is Part B Active</label>
+                                <select  name="manualMedicareIsPartBActive" class="form-control input-sm">
+                                    <option value="">--select--</option>
+                                    <option value="YES">Yes</option>
+                                    <option value="NO">No</option>
+                                    <option value="UNKNOWN">Unknown</option>
+                                </select>
+                            </div>
+                            <div class="form-group">
+                                <label for="" class="control-label">Manual Medicare Is Part C Active</label>
+                                <select  name="manualMedicareIsPartCActive" class="form-control input-sm">
+                                    <option value="">--select--</option>
+                                    <option value="YES">Yes</option>
+                                    <option value="NO">No</option>
+                                    <option value="UNKNOWN">Unknown</option>
+                                </select>
+                            </div>
+                            <div class="form-group">
+                                <label for="" class="control-label">Manual Medicare Is Inpatient</label>
+                                <select  name="manualMedicareIsInpatient" class="form-control input-sm">
+                                    <option value="">--select--</option>
+                                    <option value="YES">Yes</option>
+                                    <option value="NO">No</option>
+                                    <option value="UNKNOWN">Unknown</option>
+                                </select>
+                            </div>
+                            <div class="form-group">
+                                <label for="" class="control-label">Manual Medicare Is Hospice Or Home Health</label>
+                                <select  name="manualMedicareIsHospiceOrHomeHealth" class="form-control input-sm">
+                                    <option value="">--select--</option>
+                                    <option value="YES">Yes</option>
+                                    <option value="NO">No</option>
+                                    <option value="UNKNOWN">Unknown</option>
+                                </select>
+                            </div>
+                            <div class="form-group">
+                                <label for="" class="control-label">Manual Medicare Is Msp</label>
+                                <select  name="manualMedicareIsMsp" class="form-control input-sm">
+                                    <option value="">--select--</option>
+                                    <option value="YES">Yes</option>
+                                    <option value="NO">No</option>
+                                    <option value="UNKNOWN">Unknown</option>
+                                </select>
+                            </div>
+                            <div class="form-group">
+                                <label for="" class="control-label">Manual Medicare Msp Memo</label>
+                                <select  name="manualMedicareMspMemo" class="form-control input-sm">
+                                    <option value="">--select--</option>
+                                    <option value="YES">Yes</option>
+                                    <option value="NO">No</option>
+                                    <option value="UNKNOWN">Unknown</option>
+                                </select>
+                            </div>
+                            <div class="form-group">
+                                <label for="" class="control-label">Manual Medicare Mpb Start Date</label>
+                                <input type="date" name="manualMedicareMpbStartDate" class="form-control input-sm"/>
+                            </div>
+                            <div class="form-group">
+                                <label for="" class="control-label">Manual Medicare Mpb End Date</label>
+                                <input type="date" name="manualMedicareMpbEndDate" class="form-control input-sm"/>
+                            </div>
+                            <div class="form-group">
+                                <label for="" class="control-label">Manual Medicare Mpb Deductible</label>
+                                <input type="number" name="manualMedicareMpbDeductible" class="form-control input-sm"/>
+                            </div>
+                            <div class="form-group">
+                                <label for="" class="control-label">Manual Medicare Mpb Remaining</label>
+                                <input type="number" name="manualMedicareMpbRemaining" class="form-control input-sm"/>
+                            </div>
+                            <div class="form-group">
+                                <label for="" class="control-label">Manual Medicare Mpb Insurance Type</label>
+                                <input type="text" name="manualMedicareMpbInsuranceType" class="form-control input-sm"/>
+                            </div>
+                            <div class="form-group">
+                                <label for="" class="control-label">Manual Medicare Mpb Insurance Type Label</label>
+                                <input type="text" name="manualMedicareMpbInsuranceTypeLabel" class="form-control input-sm"/>
+                            </div>
+                            <div class="form-group">
+                                <label for="" class="control-label">Manual Medicare Mpb Coinsurance Percent</label>
+                                <input type="number" name="manualMedicareMpbCoinsurancePercent" class="form-control input-sm"/>
+                            </div>
+                            <div class="form-group">
+                                <label for="" class="control-label">Manual Medicare Mpb Info Valid Until</label>
+                                <input type="date" name="manualMedicareMpbInfoValidUntil" class="form-control input-sm"/>
+                            </div>
+                            <div class="form-group">
+                                <label for="" class="control-label">Manual Medicare Mpb Info Valid Till</label>
+                                <input type="date" name="manualMedicareMpbInfoValidTill" class="form-control input-sm"/>
+                            </div>
+                            <div class="form-group text-nowrap mb-0">
+                                <button class="btn btn-sm btn-primary" submit>Submt</button>
+                                <button class="btn btn-sm btn-default border" close>Close</button>
+                            </div>
+                        </form>
+                    </div>
+                    @endif 
+                    @if($cpc->plan_type == 'MEDICAID')
+                    <div moe relative>
+                        <a href="" start show class="">Refresh</a>
+
+                        <form url="/api/clientPrimaryCoverage/refreshCoverageForMedicaid" class="mcp-theme-1">
+                            <input type="hidden" name="uid" value="{{$cpc->uid}}" class="form-control input-sm" />
+                            <div class="form-group">
+                                <p>Refresh?</p>
+                            </div>
+                            <div class="form-group text-nowrap mb-0">
+                                <button class="btn btn-sm btn-primary" submit>Submt</button>
+                                <button class="btn btn-sm btn-default border" close>Close</button>
+                            </div>
+                        </form>
+                    </div>
+                    <div moe relative large>
+                        <a href="" start show class="">Manual Determination</a>
+
+                        <form url="/api/clientPrimaryCoverage/manualDeterminationForMedicaid" class="mcp-theme-1">
+                            <input type="hidden" name="uid" value="{{$cpc->uid}}" class="form-control input-sm" />
+                            <div class="form-group">
+                                <label for="" class="control-label">Manual Determination Strategy</label>
+                                <select  name="manualDeterminationStrategy" class="form-control input-sm">
+                                    <option value="">--select--</option>
+                                    <option value="REVIEWED_ELECTRONIC">Reviewed electronic</option>
+                                    <option value="CALLED_PAYER">Called payer</option>
+                                </select>
+                            </div>
+                            <div class="form-group">
+                                <label for="" class="control-label">Manual Determination Category</label>
+                                <select  name="manualDeterminationCategory" class="form-control input-sm">
+                                    <option value="">--select--</option>
+                                    <option value="COVERED">Covered</option>
+                                    <option value="NOT_COVERED">Not Covered</option>
+                                    <option value="INVALID">Invalid</option>
+                                    <option value="UNKNOWN">Unknown</option>
+                                </select>                        
+                            </div>
+                            <div class="form-group">
+                                <label for="" class="control-label">Manual Determination Category Memo</label>
+                                <input type="text" name="manualDeterminationCategoryMemo" class="form-control input-sm"/>
+                            </div>
+                            <div class="form-group">
+                                <label for="" class="control-label">Manual Detail Json</label>
+                                <input type="text" name="manualDetailJson" class="form-control input-sm"/>
+                            </div>
+                           
+                           
+                            <div class="form-group text-nowrap mb-0">
+                                <button class="btn btn-sm btn-primary" submit>Submt</button>
+                                <button class="btn btn-sm btn-default border" close>Close</button>
+                            </div>
+                        </form>
+                    </div>
+                    @endif 
+                    @if($cpc->plan_type == 'COMMERCIAL')
+                    <div moe relative>
+                        <a href="" start show class="">Refresh</a>
+
+                        <form url="/api/clientPrimaryCoverage/refreshCoverageForCommercial" class="mcp-theme-1">
+                            <input type="hidden" name="uid" value="{{$cpc->uid}}" class="form-control input-sm" />
+                            <div class="form-group">
+                                <p>Refresh?</p>
+                            </div>
+                            <div class="form-group text-nowrap mb-0">
+                                <button class="btn btn-sm btn-primary" submit>Submt</button>
+                                <button class="btn btn-sm btn-default border" close>Close</button>
+                            </div>
+                        </form>
+                    </div>
+                    <div moe relative large>
+                        <a href="" start show class="">Manual Determination</a>
+
+                        <form url="/api/clientPrimaryCoverage/manualDeterminationForCommercial" class="mcp-theme-1">
+                            <input type="hidden" name="uid" value="{{$cpc->uid}}" class="form-control input-sm" />
+                            <div class="form-group">
+                                <label for="" class="control-label">Manual Determination Strategy</label>
+                                <select  name="manualDeterminationStrategy" class="form-control input-sm">
+                                    <option value="">--select--</option>
+                                    <option value="REVIEWED_ELECTRONIC">Reviewed electronic</option>
+                                    <option value="CALLED_PAYER">Called payer</option>
+                                </select>
+                            </div>
+                            <div class="form-group">
+                                <label for="" class="control-label">Manual Determination Category</label>
+                                <select  name="manualDeterminationCategory" class="form-control input-sm">
+                                    <option value="">--select--</option>
+                                    <option value="COVERED">Covered</option>
+                                    <option value="NOT_COVERED">Not Covered</option>
+                                    <option value="INVALID">Invalid</option>
+                                    <option value="UNKNOWN">Unknown</option>
+                                </select>                        
+                            </div>
+                            <div class="form-group">
+                                <label for="" class="control-label">Manual Determination Category Memo</label>
+                                <input type="text" name="manualDeterminationCategoryMemo" class="form-control input-sm"/>
+                            </div>
+                            <div class="form-group">
+                                <label for="" class="control-label">Manual Detail Json</label>
+                                <input type="text" name="manualDetailJson" class="form-control input-sm"/>
+                            </div>
+                            
+                           
+                            <div class="form-group text-nowrap mb-0">
+                                <button class="btn btn-sm btn-primary" submit>Submt</button>
+                                <button class="btn btn-sm btn-default border" close>Close</button>
+                            </div>
+                        </form>
+                    </div>
+                    @endif 
+                </td>
+                <td>{{$cpc->creation_strategy}}</td>
+                <td>{{$cpc->auto_refresh_of_client_primary_coverage_id}}</td>
+                <td>{{$cpc->manual_determination_of_client_primary_coverage_id}}</td>
+                <td>{{$cpc->plan_type}}</td>
+                <td>{{$cpc->is_partbprimary}}</td>
+                <td>{{$cpc->is_manually_determined}}</td>
+                <td>{{$cpc->is_entry_error}}</td>
+                <td>{{$cpc->subscriber_name_first}}</td>
+                <td>{{$cpc->subscriber_name_last}}</td>
+                <td>{{$cpc->subscriber_sex}}</td>
+                <td>{{$cpc->subscriber_dob}}</td>
+                <td>{{$cpc->payer_member_identifier}}</td>
+                <td>{{$cpc->payer_name}}</td>
+                <td>{{$cpc->date_of_service}}</td>
+                <td>{{$cpc->auto_is_payer_member_identifier_valid}}</td>
+                <td>{{$cpc->auto_detail_json}}</td>
+                <td>{{$cpc->auto_medicare_is_partbprimary}}</td>
+                <td>{{$cpc->auto_medicare_is_partbactive}}</td>
+                <td>{{$cpc->auto_medicare_is_partcactive}}</td>
+                <td>{{$cpc->auto_medicare_is_inpatient}}</td>
+                <td>{{$cpc->auto_medicare_is_hospice_or_home_health}}</td>
+                <td>{{$cpc->auto_medicare_is_msp}}</td>
+                <td>{{$cpc->auto_medicare_msp_memo}}</td>
+                <td>{{$cpc->auto_medicare_mpb_start_date}}</td>
+                <td>{{$cpc->auto_medicare_mpb_end_date}}</td>
+                <td>{{$cpc->auto_medicare_mpb_deductible}}</td>
+                <td>{{$cpc->auto_medicare_mpb_remaining}}</td>
+                <td>{{$cpc->auto_medicare_mpb_insurance_type}}</td>
+                <td>{{$cpc->auto_medicare_mpb_insurance_type_label}}</td>
+                <td>{{$cpc->auto_medicare_mpb_coinsurance_percent}}</td>
+                <td>{{$cpc->auto_medicare_mpb_info_valid_until}}</td>
+                <td>{{$cpc->auto_medicare_mpb_info_valid_till}}</td>
+                <td>{{$cpc->auto_medicare_mpb_last_refreshed_at}}</td>
+                <td>{{$cpc->was_successful}}</td>
+                <td>{{$cpc->reject_reason_code}}</td>
+                <td>{{$cpc->reject_reason_description}}</td>
+                <td>{{$cpc->follow_up_action_code}}</td>
+                <td>{{$cpc->follow_up_action_description}}</td>
+                <td>{{$cpc->details}}</td>
+                <td>{{$cpc->is_mcn_valid_number}}</td>
+                <td>{{$cpc->address_street_line1}}</td>
+                <td>{{$cpc->address_street_line2}}</td>
+                <td>{{$cpc->address_city}}</td>
+                <td>{{$cpc->address_state}}</td>
+                <td>{{$cpc->address_zip}}</td>
+                <td>{{$cpc->is_hospice}}</td>
+                <td>{{$cpc->mcn_response_detail}}</td>
+                <td>{{$cpc->billing_address}}</td>
+                <td>{{$cpc->reason_not_partb}}</td>
+                <td>{{$cpc->reason_not_partbmemo}}</td>
+                <td>{{$cpc->is_medicare_advantage}}</td>
+                <td>{{$cpc->medicare_advantage_plan}}</td>
+                <td>{{$cpc->mpb_active}}</td>
+                <td>{{$cpc->mpb_start_date}}</td>
+                <td>{{$cpc->mpb_end_date}}</td>
+                <td>{{$cpc->mpb_deductible}}</td>
+                <td>{{$cpc->mpb_remaining}}</td>
+                <td>{{$cpc->mpb_insurance_type}}</td>
+                <td>{{$cpc->mpb_insurance_type_label}}</td>
+                <td>{{$cpc->mpb_coinsurance_percent}}</td>
+                <td>{{$cpc->mpb_info_valid_until}}</td>
+                <td>{{$cpc->mpb_info_valid_till}}</td>
+                <td>{{$cpc->mpb_last_refreshed_at}}</td>
+                <td>{{$cpc->manual_determination_strategy}}</td>
+                <td>{{$cpc->manual_determination_category}}</td>
+                <td>{{$cpc->manual_determination_category_memo}}</td>
+                <td>{{$cpc->manual_detail_json}}</td>
+                <td>{{$cpc->manual_medicare_is_partbprimary}}</td>
+                <td>{{$cpc->manual_medicare_is_partbactive}}</td>
+                <td>{{$cpc->manual_medicare_is_partcactive}}</td>
+                <td>{{$cpc->manual_medicare_is_inpatient}}</td>
+                <td>{{$cpc->manual_medicare_is_hospice_or_home_health}}</td>
+                <td>{{$cpc->manual_medicare_is_msp}}</td>
+                <td>{{$cpc->manual_medicare_msp_memo}}</td>
+                <td>{{$cpc->manual_medicare_mpb_start_date}}</td>
+                <td>{{$cpc->manual_medicare_mpb_end_date}}</td>
+                <td>{{$cpc->manual_medicare_mpb_deductible}}</td>
+                <td>{{$cpc->manual_medicare_mpb_remaining}}</td>
+                <td>{{$cpc->manual_medicare_mpb_insurance_type}}</td>
+                <td>{{$cpc->manual_medicare_mpb_insurance_type_label}}</td>
+                <td>{{$cpc->manual_medicare_mpb_coinsurance_percent}}</td>
+                <td>{{$cpc->manual_medicare_mpb_info_valid_until}}</td>
+                <td>{{$cpc->manual_medicare_mpb_info_valid_till}}</td>
+                <td>{{$cpc->manual_medicare_mpb_last_refreshed_at}}</td>
+                <td>{{$cpc->auto_medicare_result_id}}</td>
+            </tr>
+            @endforeach
+        </tbody>
+    </table>
+</div>
+@endsection

+ 168 - 42
resources/views/app/patient/dashboard.blade.php

@@ -36,32 +36,67 @@
                 <div class="pt-2 mt-2 border-top">
                     <div class="d-flex align-items-center pb-2">
                         <h6 class="my-0 font-weight-bold text-secondary">Allergies</h6>
-                        <span class="mx-2 text-secondary">|</span>
-                        @include('app.patient.canvas-sections.canvas-editor-modal', ['key' => 'allergies'])
+                        <div class="px-2 font-weight-bold alert alert-warning text-sm my-0 ml-2 py-1">Deprecated</div>
                     </div>
                     <div class="bg-light border p-2 mb-3">
                         @include('app.patient.canvas-sections.allergies.summary')
                     </div>
                 </div>
 
+                <!-- allergies - point -->
+                <?php
+                $allergies = \App\Models\Point::getPointsOfCategory($patient, "ALLERGY");
+                ?>
+                <div class="pt-2 mt-2">
+                    <div class="d-flex align-items-center pb-2">
+                        <h6 class="my-0 font-weight-bold text-secondary">Allergies</h6>
+                        <div class="px-2 font-weight-bold alert alert-info text-sm my-0 ml-2 py-1">New</div>
+                    </div>
+                    <div class="bg-light border p-2 mb-3">
+                        @foreach($allergies as $allergy)
+                            <div class="mb-1">
+                                <b><?= !!@($allergy->data->name) ? @($allergy->data->name) : '-' ?></b>
+                                <?= !!@($allergy->data->description) ? '/&nbsp;' . @($allergy->data->description) : '' ?>
+                            </div>
+                        @endforeach
+                        @if(!count($allergies))
+                            <div class="text-secondary">Nothing here yet</div>
+                        @endif
+                    </div>
+                </div>
+
                 {{-- canvas based rx --}}
                 <div class="pt-2 mt-2 border-top">
                     <div class="d-flex align-items-center pb-2">
                         <h6 class="my-0 font-weight-bold text-secondary">Current Medications</h6>
-                        <span class="mx-2 text-secondary">|</span>
-                        @include('app.patient.canvas-sections.canvas-editor-modal', ['key' => 'rx', 'class' => 'wide'])
-                        <span class="mx-2 text-secondary">|</span>
-                        <a href="/patients/view/{{$patient->uid}}/tickets/erx?popupmode=1"
-                           native target="_blank"
-                           class="ticket-popup-trigger d-block text-nowrap mr-3">
-                            Erx/Orders
-                        </a>
+                        <div class="px-2 font-weight-bold alert alert-warning text-sm my-0 ml-2 py-1">Deprecated</div>
                     </div>
                     <div class="bg-light border p-2 mb-3">
                         @include('app.patient.canvas-sections.rx.summary')
                     </div>
                 </div>
-                <div class="stag-popup stag-popup-lg ticket-popup mcp-theme-1" stag-popup-key="ticket-popup"></div>
+
+                <!-- meds - point -->
+                <?php
+                $medications = \App\Models\Point::getPointsOfCategory($patient, "MEDICATION");
+                ?>
+                <div class="pt-2 mt-2">
+                    <div class="d-flex align-items-center pb-2">
+                        <h6 class="my-0 font-weight-bold text-secondary">Current Medications</h6>
+                        <div class="px-2 font-weight-bold alert alert-info text-sm my-0 ml-2 py-1">New</div>
+                    </div>
+                    <div class="bg-light border p-2 mb-3">
+                        @foreach($medications as $medication)
+                            <div class="mb-1">
+                                <b><?= !!@($medication->data->name) ? @($medication->data->name) : '-' ?></b>
+                                <?= !!@($medication->data->frequency) ? '/&nbsp;' . @($medication->data->frequency) : '' ?>
+                            </div>
+                        @endforeach
+                        @if(!count($medications))
+                            <div class="text-secondary">Nothing here yet</div>
+                        @endif
+                    </div>
+                </div>
 
                 {{-- rm reasons --}}
                 <div class="pt-2 mt-2 border-top">
@@ -193,14 +228,35 @@
                 <div class="pt-2 border-top">
                     <div class="d-flex align-items-center pb-2">
                         <h6 class="my-0 font-weight-bold text-secondary">Vitals</h6>
-                        <span class="mx-2 text-secondary">|</span>
-                        @include('app.patient.canvas-sections.canvas-editor-modal', ['key' => 'vitals', 'class' => 'narrow'])
+                        <div class="px-2 font-weight-bold alert alert-warning text-sm my-0 ml-2 py-1">Deprecated</div>
                     </div>
                     <div class="bg-light border p-2 mb-3">
                         @include('app.patient.canvas-sections.vitals.summary')
                     </div>
                 </div>
 
+                <!-- vitals - point -->
+                <?php $latestVitals = \App\Models\Point::where('client_id', $patient->id)->where('category', 'VITALS')->orderBy('id', 'DESC')->first(); ?>
+                <div class="pt-2 mt-2">
+                    <div class="d-flex align-items-center pb-2">
+                        <h6 class="my-0 font-weight-bold text-secondary">Vitals
+                            @if(!!$latestVitals && $latestVitals->note && $latestVitals->note->effective_dateest)
+                                <span class="text-secondary font-weight-normal pl-1">(as on
+                                    <a href="{{route('patients.view.notes.view.dashboard', ['patient' => $patient, 'note' => $latestVitals->note])}}">{{friendlier_date($latestVitals->note->effective_dateest)}}</a>)
+                                </span>
+                            @endif
+                        </h6>
+                        <div class="px-2 font-weight-bold alert alert-info text-sm my-0 ml-2 py-1">New</div>
+                    </div>
+                    <div class="bg-light border p-2 mb-3">
+                        @if(!!$latestVitals)
+                            @include('app.patient.partials.latest-vitals', ['patient' => $patient, 'point' => $latestVitals])
+                        @else
+                            <div class="text-secondary">Nothing here yet</div>
+                        @endif
+                    </div>
+                </div>
+
             </div>
             <div class="col-6">
 
@@ -211,75 +267,126 @@
                 <div class="pt-2 mt-2 border-top">
                     <div class="d-flex align-items-center pb-2">
                         <h6 class="my-0 font-weight-bold text-secondary">Current Problems / Focus Areas</h6>
-                        <span class="mx-2 text-secondary">|</span>
-                        @include('app.patient.canvas-sections.canvas-editor-modal', ['key' => 'dx', 'class' => 'wide'])
+                        <div class="px-2 font-weight-bold alert alert-warning text-sm my-0 ml-2 py-1">Deprecated</div>
                     </div>
                     <div class="bg-light border p-2 mb-3">
                         @include('app.patient.canvas-sections.dx.summary')
                     </div>
                 </div>
 
-                {{--<div class="mt-2">
-                    <div class="d-flex align-items-center mb-2 py-2 border-top border-bottom">
-                        <h6 class="my-0 font-weight-bold text-secondary">History</h6>
-                        <span class="mx-2 text-secondary">|</span>
-                        <a start show class="py-0 font-weight-normal"
-                           href="/patients/view/{{ $patient->uid }}/history">
-                            View All
-                        </a>
+                <!-- probs - point -->
+                <?php
+                $problems = \App\Models\Point::getPointsOfCategory($patient, "PROBLEM");
+                ?>
+                <div class="pt-2 mt-2">
+                    <div class="d-flex align-items-center pb-2">
+                        <h6 class="my-0 font-weight-bold text-secondary">Current Problems / Focus Areas</h6>
+                        <div class="px-2 font-weight-bold alert alert-info text-sm my-0 ml-2 py-1">New</div>
                     </div>
-                </div>--}}
+                    <div class="bg-light border p-2 mb-3">
+                        @foreach($problems as $problem)
+                            <div class="mb-1">
+                                <b><?= !!@($problem->data->name) ? @($problem->data->name) : '-' ?></b>
+                                <?= !!@($problem->data->icd) ? '/&nbsp;' . @($problem->data->icd) : '' ?>
+                                <?= !!@($problem->data->description) ? '/&nbsp;' . @($problem->data->description) : '' ?>
+                            </div>
+                        @endforeach
+                        @if(!count($problems))
+                            <div class="text-secondary">Nothing here yet</div>
+                        @endif
+                    </div>
+                </div>
 
                 {{-- history_medical --}}
                 <div class="pt-2 mt-2 border-top">
                     <div class="d-flex align-items-center pb-2">
                         <h6 class="my-0 font-weight-bold text-secondary">Medical History</h6>
-                        <span class="mx-2 text-secondary">|</span>
-                        @include('app.patient.canvas-sections.canvas-editor-modal', ['key' => 'pmhx'])
+                        <div class="px-2 font-weight-bold alert alert-warning text-sm my-0 ml-2 py-1">Deprecated</div>
                     </div>
                     <div class="bg-light border p-2 mb-3">
                         @include('app.patient.canvas-sections.pmhx.summary')
                     </div>
                 </div>
 
+                <!-- pmhx - point -->
+                <div class="pt-2 mt-2">
+                    <div class="d-flex align-items-center pb-2">
+                        <h6 class="my-0 font-weight-bold text-secondary">Medical History</h6>
+                        <div class="px-2 font-weight-bold alert alert-info text-sm my-0 ml-2 py-1">New</div>
+                    </div>
+                    <div class="bg-light border p-2 mb-3">
+                        @include('app.patient.segment-templates.past_medical_history.summary', compact('patient'))
+                    </div>
+                </div>
+
                 {{-- history_surgical --}}
-                <div class="mt-2">
+                <div class="mt-2 border-top pt-2">
                     <div class="d-flex align-items-center pb-2">
                         <h6 class="my-0 font-weight-bold text-secondary">Surgical History</h6>
-                        <span class="mx-2 text-secondary">|</span>
-                        @include('app.patient.canvas-sections.canvas-editor-modal', ['key' => 'pshx'])
+                        <div class="px-2 font-weight-bold alert alert-warning text-sm my-0 ml-2 py-1">Deprecated</div>
                     </div>
                     <div class="bg-light border p-2 mb-3">
                         @include('app.patient.canvas-sections.pshx.summary')
                     </div>
                 </div>
 
+                <!-- pshx - point -->
+                <div class="pt-2 mt-2">
+                    <div class="d-flex align-items-center pb-2">
+                        <h6 class="my-0 font-weight-bold text-secondary">Surgical History</h6>
+                        <div class="px-2 font-weight-bold alert alert-info text-sm my-0 ml-2 py-1">New</div>
+                    </div>
+                    <div class="bg-light border p-2 mb-3">
+                        @include('app.patient.segment-templates.history_surgical.summary', compact('patient'))
+                    </div>
+                </div>
+
                 {{-- history_family --}}
-                <div class="mt-2">
+                <div class="mt-2 border-top pt-2">
                     <div class="d-flex align-items-center pb-2">
                         <h6 class="my-0 font-weight-bold text-secondary">Family History</h6>
-                        <span class="mx-2 text-secondary">|</span>
-                        @include('app.patient.canvas-sections.canvas-editor-modal', ['key' => 'fhx'])
+                        <div class="px-2 font-weight-bold alert alert-warning text-sm my-0 ml-2 py-1">Deprecated</div>
                     </div>
                     <div class="bg-light border p-2 mb-3">
                         @include('app.patient.canvas-sections.fhx.summary')
                     </div>
                 </div>
 
+                <!-- fhx - point -->
+                <div class="pt-2 mt-2">
+                    <div class="d-flex align-items-center pb-2">
+                        <h6 class="my-0 font-weight-bold text-secondary">Family History</h6>
+                        <div class="px-2 font-weight-bold alert alert-info text-sm my-0 ml-2 py-1">New</div>
+                    </div>
+                    <div class="bg-light border p-2 mb-3">
+                        @include('app.patient.segment-templates.history_family.summary', compact('patient'))
+                    </div>
+                </div>
+
                 {{-- history_social --}}
-                <div class="mt-2">
+                <div class="mt-2 border-top pt-2">
                     <div class="d-flex align-items-center pb-2">
                         <h6 class="my-0 font-weight-bold text-secondary">Social History</h6>
-                        <span class="mx-2 text-secondary">|</span>
-                        @include('app.patient.canvas-sections.canvas-editor-modal', ['key' => 'sochx'])
+                        <div class="px-2 font-weight-bold alert alert-warning text-sm my-0 ml-2 py-1">Deprecated</div>
                     </div>
                     <div class="bg-light border p-2 mb-3">
                         @include('app.patient.canvas-sections.sochx.summary')
                     </div>
                 </div>
 
+                <!-- sochx - point -->
+                <div class="pt-2 mt-2">
+                    <div class="d-flex align-items-center pb-2">
+                        <h6 class="my-0 font-weight-bold text-secondary">Social History</h6>
+                        <div class="px-2 font-weight-bold alert alert-info text-sm my-0 ml-2 py-1">New</div>
+                    </div>
+                    <div class="bg-light border p-2 mb-3">
+                        @include('app.patient.segment-templates.history_social.summary', compact('patient'))
+                    </div>
+                </div>
+
                 {{-- history_ob_and_preg --}}
-                <div class="pl-2 mt-2">
+                <div class="pl-2 mt-2 border-top pt-2">
                     <div class="d-flex align-items-center pb-2">
                         <h6 class="my-0 font-weight-bold">OB & Pregnancy</h6>
                         <span class="mx-2 text-secondary">|</span>
@@ -652,20 +759,39 @@
                     </div>
                 </div>
 
-                {{-- care-team --}}
-                {{--@include('app/patient/partials/care-team')--}}
-
-                {{-- canvas based dx --}}
+                {{-- canvas based careteam --}}
                 <div class="pt-2 mt-2 border-top">
                     <div class="d-flex align-items-center pb-2">
                         <h6 class="my-0 font-weight-bold text-secondary">Care Team</h6>
-                        <span class="mx-2 text-secondary">|</span>
-                        @include('app.patient.canvas-sections.canvas-editor-modal', ['key' => 'care-team', 'class' => 'wide'])
+                        <div class="px-2 font-weight-bold alert alert-warning text-sm my-0 ml-2 py-1">Deprecated</div>
                     </div>
                     <div class="bg-light border p-2 mb-3">
                         @include('app.patient.canvas-sections.care-team.summary')
                     </div>
                 </div>
+
+                <!-- careteam - point -->
+                <?php
+                $careTeamMembers = \App\Models\Point::getPointsOfCategory($patient, "CARE_TEAM_MEMBER");
+                ?>
+                <div class="pt-2 mt-2">
+                    <div class="d-flex align-items-center pb-2">
+                        <h6 class="my-0 font-weight-bold text-secondary">Care Team</h6>
+                        <div class="px-2 font-weight-bold alert alert-info text-sm my-0 ml-2 py-1">New</div>
+                    </div>
+                    <div class="bg-light border p-2 mb-3">
+                        @foreach($careTeamMembers as $careTeamMember)
+                            <div class="mb-1">
+                                <b><?= !!@($careTeamMember->data->name) ? @($careTeamMember->data->name) : '-' ?></b>
+                                <?= !!@($careTeamMember->data->spacialty) ? '/&nbsp;' . @($careTeamMember->data->spacialty) . '<br>' : '' ?>
+                                <?= !!@($careTeamMember->data->organization) ? '/&nbsp;' . @($careTeamMember->data->organization) . '<br>' : '' ?>
+                            </div>
+                        @endforeach
+                        @if(!count($careTeamMembers))
+                            <div class="text-secondary">Nothing here yet</div>
+                        @endif
+                    </div>
+                </div>
             </div>
         </div>
         <?php /* <div class="row my-3">

+ 19 - 15
resources/views/app/patient/incoming-reports.blade.php

@@ -1,6 +1,6 @@
 @extends ('layouts.patient')
 @section('inner-content')
-    <div>
+    <div id="incoming-reports">
         <div class="d-flex align-items-center pb-2">
             <h4 class="font-weight-bold m-0">Incoming Reports</h4>
             <span class="mx-2 text-secondary">|</span>
@@ -23,7 +23,7 @@
                     </div>
                     <div class="mb-2">
                         <label for="" class="text-sm text-secondary mb-1">Report Date</label>
-                        <input type="date" class="form-control form-control-sm" name="reportDate"
+                        <input type="text" class="form-control form-control-sm stag-dp" name="reportDate"
                                value="" placeholder="Report Date">
                     </div>
                     <div class="mb-2">
@@ -60,8 +60,9 @@
                     <thead>
                     <tr>
                         <th class="px-2 text-secondary">Created</th>
+                        <th class="px-2 text-secondary">Pro</th>
                         <th class="px-2 text-secondary">Title</th>
-<!--                        <th class="px-2 text-secondary">Report</th>-->
+                        <th class="px-2 text-secondary">Report Date</th>
                         <th class="px-2 text-secondary">Sign</th>
                         <th class="px-2 text-secondary">Category</th>
                     </tr>
@@ -70,24 +71,16 @@
                     @foreach($patient->incomingReports as $document)
                         <tr class="{{$document->is_entry_error ? 'entry-error' : ''}} {{@$currentReport->uid === $document->uid ? 'bg-aliceblue' : ''}}">
                             <td class="px-2">{{ friendly_date_time($document->created_at, false) }}</td>
+                            <td class="px-2">
+                                {{$document->hcp ? $document->hcp->displayName() : '-'}}
+                            </td>
                             <td class="px-2">
                                 <a href="{{route('patients.view.incoming-reports', ['patient' => $patient, 'currentReport' => $document])}}"
                                    class="{{@$currentReport->uid === $document->uid ? 'font-weight-bold' : ''}}">
                                     {{ $document->title ? $document->title : '(not set)' }}
                                 </a>
                             </td>
-{{--                            <td class="px-2">--}}
-{{--                                <div class="d-flex align-items-center">--}}
-{{--                                    <a class="pdf-viewer-trigger" native target="_blank"--}}
-{{--                                       href="/api/incomingReport/download/{{ $document->uid }}"--}}
-{{--                                       title="View">View</a>--}}
-{{--                                    @if($document->is_entry_error)--}}
-{{--                                        <span class="ml-auto text-danger on-hover-opaque" title="Entry Error">--}}
-{{--                                    <i class="fa fa-exclamation-triangle"></i>--}}
-{{--                                </span>--}}
-{{--                                    @endif--}}
-{{--                                </div>--}}
-{{--                            </td>--}}
+                            <td class="px-2">{{ friendly_date_time($document->report_date, false) }}</td>
                             <td class="px-2">
                                 @if(!$document->has_hcp_pro_signed)
                                     -
@@ -503,5 +496,16 @@
             });
             return false;
         }
+        (function() {
+            function init() {
+                $('#incoming-reports').find('input.stag-dp')
+                    .prop('readonly', true)
+                    .addClass('bg-white')
+                    .datepicker({
+                        dateFormat: 'yy-mm-dd'
+                    });
+            }
+            addMCInitializer('incoming-reports', init, '#incoming-reports')
+        }).call(window);
     </script>
 @endsection

+ 435 - 0
resources/views/app/patient/medications-center.blade.php

@@ -0,0 +1,435 @@
+<?php
+
+use App\Models\Point;
+use App\Models\Client;
+use App\Models\Note;
+use App\Models\Segment;
+
+/** @var Client $patient */
+/** @var Note $note */
+
+$points = Point
+    ::where('client_id', $patient->id)
+    ->where('category', 'MEDICATION')
+    ->where('is_removed_due_to_entry_error', false)
+    ->orderBy('is_removed')
+    ->orderBy('removal_effective_date', 'DESC')
+    ->orderBy('created_at')
+    ->get();
+foreach ($points as $point) {
+    if ($point->data) {
+        $point->data = json_decode($point->data);
+    }
+}
+$medications = $points;
+
+?>
+
+<div class="mt-3 p-3 border-top min-height-500px" id="medications-center-{{$note->id}}">
+    <div>
+
+        <table class="table table-sm table-bordered table-striped mb-0 bg-white mb-2">
+            <thead>
+            <tr class="">
+                <th class="border-bottom-0 text-secondary">Name</th>
+                <th class="border-bottom-0 text-secondary">Frequency</th>
+                <th class="border-bottom-0 text-secondary">Active?</th>
+                <th class="border-bottom-0 text-secondary">Edit</th>
+                <th class="border-bottom-0 text-secondary">Delete</th>
+                <th class="border-bottom-0 text-secondary">Started</th>
+                <th class="border-bottom-0 text-secondary">Ended</th>
+                <th class="border-bottom-0 text-secondary">Last Review</th>
+                <th class="border-bottom-0 text-secondary">Last Plan</th>
+            </tr>
+            </thead>
+            <?php foreach($medications as $medication): ?>
+            <?php $point = $medication; ?>
+            <tr class="{{$medication->is_removed ? 'on-hover-opaque' : ''}}">
+                <td>
+                    <div class="d-flex align-items-baseline">
+                        @if($medication->is_removed)
+                            <i class="text-warning-mellow fa fa-circle text-sm on-hover-opaque mr-2"></i>
+                        @else
+                            <i class="text-success fa fa-circle text-sm on-hover-opaque mr-2"></i>
+                        @endif
+                        <div>
+                            <b><?= !!@($medication->data->name) ? @($medication->data->name) : '-' ?></b>
+                            @if(!$medication->is_removed && $medication->added_in_note_id === $note->id)
+                                <div class="mt-1 text-sm text-secondary">Added during this visit
+                                    @if($medication->addition_reason_category === 'ON_INTAKE')
+                                        (existing)
+                                    @elseif($medication->addition_reason_category === 'DURING_VISIT')
+                                        (new)
+                                    @endif
+                                </div>
+                            @endif
+                            @if($medication->is_removed && ($medication->added_in_note_id !== $note->id && $medication->removed_in_note_id === $note->id))
+                                <div class="mt-1 text-sm text-secondary">Discontinued during this visit</div>
+                            @endif
+                        </div>
+                    </div>
+                </td>
+                <td>
+                    <?= !!@($medication->data->frequency) ? @($medication->data->frequency) : '-' ?>
+                </td>
+                <td>
+                    @if($medication->is_removed)
+                        NO
+                    @else
+                        <b>YES</b>
+                    @endif
+                </td>
+                <td>
+                    @if($medication->added_in_note_id === $note->id)
+                        <div moe wide>
+                            <a start show href="#" title="Edit">Edit</a>
+                            <form url="/api/visitPoint/updateTopLevel" class="mcp-theme-1 frm-edit-medication">
+                                <input type="hidden" name="uid" value="<?= $medication->uid ?>">
+                                <input type="hidden" name="noteUid" value="<?= $note->uid ?>">
+                                <p class="mb-2"><b>Update Medication</b></p>
+
+                                <input type="hidden" name="data">
+
+                                <input type="hidden" data-name="medId" value="{{@$medication->data->medId}}">
+                                <input type="hidden" data-name="routedMedId" value="{{@$medication->data->routedMedId}}">
+                                <input type="hidden" data-name="routedDosageFormMedId" value="{{@$medication->data->routedDosageFormMedId}}">
+                                <input type="hidden" data-name="gcnSeqno" value="{{@$medication->data->gcnSeqno}}">
+
+                                <div class="mb-2">
+                                    <label class="text-sm text-secondary mb-1">Drug</label>
+                                    <input type="text" class="form-control form-control-sm min-width-unset prescription-medication"
+                                           data-name="name"
+                                           value="{{@$medication->data->name}}"
+                                           stag-suggest
+                                           stag-suggest-ep="/fdb-med-suggest-v2/json">
+                                </div>
+
+                                <div class="mb-2">
+                                    <label class="text-sm text-secondary mb-1">Frequency</label>
+                                    <input type="text" class="form-control form-control-sm min-width-unset"
+                                           data-option-list="frequency-options" data-field="frequency"
+                                           value="{{@$medication->data->frequency}}"
+                                           data-name="frequency">
+                                    <div id="frequency-options" class="data-option-list">
+                                        <div>Once a day</div>
+                                        <div>Twice a day</div>
+                                    </div>
+                                </div>
+
+                                <div class="mb-2">
+                                    <label class="text-sm text-secondary mb-1">Existing / New</label>
+                                    <select class="form-control form-control-sm" name="additionReasonCategory" required>
+                                        <option value="">-- select --</option>
+                                        <option value="ON_INTAKE" {{$medication->addition_reason_category === 'ON_INTAKE' ? 'selected' : ''}}>Existing (Patient was already on this)</option>
+                                        <option value="DURING_VISIT" {{$medication->addition_reason_category === 'DURING_VISIT' ? 'selected' : ''}}>New (Prescribed during this visit)</option>
+                                    </select>
+                                </div>
+
+                                <div class="mb-2">
+                                    <label class="text-sm text-secondary mb-1">Description</label>
+                                    <textarea rows="1" data-name="description" class="form-control form-control-sm">{{@$medication->data->description}}</textarea>
+                                </div>
+
+                                <div>
+                                    <button type="submit" class="btn-save-medication btn btn-sm btn-primary mr-2">Save</button>
+                                    <button cancel class="btn btn-sm btn-default border">Cancel</button>
+                                </div>
+                            </form>
+                        </div>
+                    @endif
+                </td>
+                <td>
+                    @if(!$medication->is_removed)
+                        @if($medication->added_in_note_id === $note->id)
+                            <div moe>
+                                <a start show href="#" title="Delete">Delete</a>
+                                <form url="/api/visitPoint/updateTopLevel" class="mcp-theme-1">
+                                    <input type="hidden" name="uid" value="<?= $medication->uid ?>">
+                                    <input type="hidden" name="noteUid" value="<?= $note->uid ?>">
+                                    <input type="hidden" name="isRemoved" value="1">
+                                    <input type="hidden" name="isRemovedDueToEntryError" value="1">
+                                    <input type="hidden" name="removalReasonMemo" value="Entry Error">
+                                    <input type="hidden" name="removalEffectiveDate" value="<?= date('Y-m-d') ?>">
+                                    <p class="mb-2"><b>Delete this medication?</b></p>
+                                    <div>
+                                        <button submit class="btn btn-sm btn-danger mr-2">Delete</button>
+                                        <button cancel class="btn btn-sm btn-default border">Cancel</button>
+                                    </div>
+                                </form>
+                            </div>
+                        @else
+                            <div moe>
+                                <a start show href="#" title="Discontinue">Discontinue</a>
+                                <form url="/api/visitPoint/updateTopLevel" class="mcp-theme-1">
+                                    <input type="hidden" name="uid" value="<?= $medication->uid ?>">
+                                    <input type="hidden" name="noteUid" value="<?= $note->uid ?>">
+                                    <input type="hidden" name="isRemoved" value="1">
+                                    <input type="hidden" name="isRemovedDueToEntryError" value="0">
+                                    <p class="mb-2"><b>Discontinue this medication?</b></p>
+                                    <div class="mb-2">
+                                        <label class="text-sm text-secondary mb-1">Already stopped / Stop now</label>
+                                        <select class="form-control form-control-sm" name="removalReasonCategory" required>
+                                            <option value="">-- select --</option>
+                                            <option value="ON_INTAKE">Already stopped (before this visit)</option>
+                                            <option value="DURING_VISIT">Stop now</option>
+                                        </select>
+                                    </div>
+                                    <div class="mb-2">
+                                        <label class="text-sm text-secondary mb-1">Removal Reason</label>
+                                        <textarea name="removalReasonMemo" class="form-control form-control-sm" rows="2"></textarea>
+                                    </div>
+                                    <div class="mb-2">
+                                        <label class="text-sm text-secondary mb-1">Removal Effective Date</label>
+                                        <input type="date" name="removalEffectiveDate"
+                                               value="<?= date('Y-m-d') ?>"
+                                               max="<?= date('Y-m-d') ?>"
+                                               class="form-control form-control-sm">
+                                    </div>
+                                    <div>
+                                        <button submit class="btn btn-sm btn-danger mr-2">Delete</button>
+                                        <button cancel class="btn btn-sm btn-default border">Cancel</button>
+                                    </div>
+                                </form>
+                            </div>
+                        @endif
+                    @endif
+                </td>
+                <td>
+                    <?= !!@($medication->data->start_date) ? @($medication->data->start_date) : '-' ?>
+                    @if(!!@($medication->data->prescriber))
+                        <div class="mt-1 text-sm text-secondary">By: <?= !!@($medication->data->prescriber) ? @($medication->data->prescriber) : '-' ?></div>
+                    @endif
+                </td>
+                <td>
+                    <?= !!@($medication->removal_effective_date) ? @($medication->removal_effective_date) : '-' ?>
+                    @if(!!@($medication->removal_reason_memo))
+                        <div class="mt-1 text-sm text-secondary">By: <?= !!@($medication->removal_reason_memo) ? @($medication->removal_reason_memo) : '-' ?></div>
+                    @endif
+                </td>
+                <td>
+                    <div class="d-flex align-items-start">
+                        <div class="flex-grow-1">
+                            <?php
+                            $point = $medication;
+                            include resource_path('views/app/patient/segment-templates/_child_review/last-review.php');
+                            ?>
+                        </div>
+                        <a class="px-2 view-review-log"
+                           native target="_blank"
+                           open-in-stag-popup
+                           popup-style="stag-popup-md"
+                           title="Review log<?= !!@($medication->data->name) ? ' for ' . @($medication->data->name) : '' ?>"
+                           href="/point/review-log/<?= $medication->uid ?>?popupmode=1">
+                            <i class="fa fa-history"></i>
+                        </a>
+                    </div>
+                </td>
+                <td>
+                    <div class="d-flex align-items-start">
+                        <div class="flex-grow-1">
+                            <?php
+                            include resource_path('views/app/patient/segment-templates/_child_plan/last-plan.php');
+                            ?>
+                        </div>
+                        <a class="px-2 view-review-log"
+                           native target="_blank"
+                           open-in-stag-popup
+                           popup-style="stag-popup-md"
+                           title="Plan log<?= !!@($medication->data->name) ? ' for ' . @($medication->data->name) : '' ?>"
+                           href="/point/plan-log/<?= $medication->uid ?>?popupmode=1">
+                            <i class="fa fa-history"></i>
+                        </a>
+                    </div>
+                </td>
+            </tr>
+            <?php endforeach; ?>
+        </table>
+
+        <div class="d-flex align-items-center">
+            <div class="mt-1 w-100 border p-2 bg-aliceblue border-info rounded">
+                <!--<a href="#" start show class="btn btn-sm btn btn-outline-primary">+ Add new medication, prescribed during this visit</a>-->
+                <form action="/api/visitPoint/addTopLevel" class="mcp-theme-1 w-100" id="frm-add-medication">
+                    <input type="hidden" name="noteUid" value="<?= $note->uid ?>">
+                    <input type="hidden" name="category" value="MEDICATION">
+                    <input type="hidden" name="data">
+
+                    <input type="hidden" data-name="medId">
+                    <input type="hidden" data-name="routedMedId">
+                    <input type="hidden" data-name="routedDosageFormMedId">
+                    <input type="hidden" data-name="gcnSeqno">
+
+                    <p class="mb-2"><b>Add Medication</b></p>
+
+                    <div class="d-flex align-items-start">
+
+                        <div class="mb-2 w-25">
+                            <label class="text-sm text-secondary mb-1">Name</label>
+                            <input type="text"
+                                   data-name="name"
+                                   class="form-control form-control-sm"
+                                   stag-suggest
+                                   stag-suggest-bottom-left
+                                   stag-suggest-ep="/fdb-med-suggest-v2/json"
+                                   required>
+                        </div>
+                        <div class="mb-2 ml-2">
+                            <label class="text-sm text-secondary mb-1">Frequency</label>
+                            <input type="text" class="form-control form-control-sm" data-name="frequency"
+                                   data-option-list="frequency-options" autocomplete="off">
+                            <div id="frequency-options" class="data-option-list">
+                                <div>Once a day</div>
+                                <div>Twice a day</div>
+                            </div>
+                        </div>
+                        <div class="mb-2 ml-2">
+                            <label class="text-sm text-secondary mb-1">Existing / New</label>
+                            <select class="form-control form-control-sm" name="additionReasonCategory" required>
+                                <option value="">-- select --</option>
+                                <option value="ON_INTAKE">Existing (Patient was already on this)</option>
+                                <option value="DURING_VISIT">New (Prescribed during this visit)</option>
+                            </select>
+                        </div>
+                        <div class="mb-2 ml-2 flex-grow-1">
+                            <label class="text-sm text-secondary mb-1">Description</label>
+                            <textarea rows="1" data-name="description" class="form-control form-control-sm"></textarea>
+                        </div>
+
+                    </div>
+
+                    <div class="d-flex align-items-center">
+                        <button type="submit" class="btn btn-sm btn-primary mr-2">Submit</button>
+                        <button type="button" class="btn btn-sm btn-default bg-white border mr-2" onclick="closeStagPopup()">Close</button>
+                    </div>
+                </form>
+            </div>
+        </div>
+    </div>
+</div>
+
+<script>
+    (function() {
+        function init() {
+            let parentSegment = $('#medications-center-{{$note->id}}');
+            parentSegment.find('input[stag-suggest][data-name="name"]')
+                .off('stag-suggest-selected')
+                .on('stag-suggest-selected', (_e, _input, _data) => {
+                    $(_input).closest('form').find('input[data-name="routedMedId"]').val(_data.routed_med_id);
+                    $(_input).closest('form').find('input[data-name="routedDosageFormMedId"]').val(_data.routed_dosage_form_med_id);
+                    $(_input).closest('form').find('input[data-name="gcnSeqno"]').val(_data.gcn_seqno);
+                    $(_input).closest('form').find('input[data-name="medId"]').val(_data.medid);
+                    return false;
+                });
+
+            parentSegment.find('#frm-add-medication')
+                .off('submit')
+                .on('submit', function () {
+
+                    let form = $(this);
+
+                    if (!form[0].checkValidity()) {
+                        form[0].reportValidity();
+                        return false;
+                    }
+
+                    // add [data-name] values to payload
+                    let dataField = form.find('[name="data"]').first();
+                    let parsed = null;
+                    if(dataField.val()) {
+                        parsed = JSON.parse(dataField.val());
+                    }
+                    form.find('[data-name]').each(function() {
+                        if(!parsed) parsed = {};
+
+                        let keys = $(this).attr('data-name').split('->');
+                        let currentNode = parsed;
+                        for (let i = 0; i < keys.length; i++) {
+                            if(i !== keys.length - 1) {
+                                if(typeof currentNode[keys[i]] === 'undefined') {
+                                    currentNode[keys[i]] = {};
+                                }
+                                currentNode = currentNode[keys[i]];
+                            }
+                            else {
+                                if($(this).is(':checkbox')) {
+                                    currentNode[keys[i]] = $(this).prop('checked');
+                                }
+                                else {
+                                    currentNode[keys[i]] = $(this).val();
+                                }
+                            }
+                        }
+
+                    });
+                    if(parsed) {
+                        dataField.val(JSON.stringify(parsed));
+                    }
+
+                    $.post(form.attr('action'), form.serialize(), _data => {
+                        if(!hasResponseError(_data)) {
+                            hideMask();
+                            refreshDynamicStagPopup();
+                            $('.visit-segment[data-segment-template-name="intake_medications"]').find('.refresh-segment').trigger('click');
+                        }
+                    }, 'json');
+                    return false;
+                });
+
+            parentSegment.find('.frm-edit-medication')
+                .off('submit')
+                .on('submit', function () {
+
+                    let form = $(this);
+
+                    if (!form[0].checkValidity()) {
+                        form[0].reportValidity();
+                        return false;
+                    }
+
+                    // add [data-name] values to payload
+                    let dataField = form.find('[name="data"]').first();
+                    let parsed = null;
+                    if(dataField.val()) {
+                        parsed = JSON.parse(dataField.val());
+                    }
+                    form.find('[data-name]').each(function() {
+                        if(!parsed) parsed = {};
+
+                        let keys = $(this).attr('data-name').split('->');
+                        let currentNode = parsed;
+                        for (let i = 0; i < keys.length; i++) {
+                            if(i !== keys.length - 1) {
+                                if(typeof currentNode[keys[i]] === 'undefined') {
+                                    currentNode[keys[i]] = {};
+                                }
+                                currentNode = currentNode[keys[i]];
+                            }
+                            else {
+                                if($(this).is(':checkbox')) {
+                                    currentNode[keys[i]] = $(this).prop('checked');
+                                }
+                                else {
+                                    currentNode[keys[i]] = $(this).val();
+                                }
+                            }
+                        }
+
+                    });
+                    if(parsed) {
+                        dataField.val(JSON.stringify(parsed));
+                    }
+
+                    $.post(form.attr('url'), form.serialize(), _data => {
+                        if(!hasResponseError(_data)) {
+                            hideMask();
+                            refreshDynamicStagPopup();
+                            $('.visit-segment[data-segment-template-name="intake_medications"]').find('.refresh-segment').trigger('click');
+                        }
+                    }, 'json');
+                    return false;
+                });
+
+            initStagSuggest();
+        }
+        addMCInitializer('medications-center-{{$note->id}}', init, '#medications-center-{{$note->id}}')
+    }).call(window);
+</script>

+ 67 - 59
resources/views/app/patient/note/_create-bill.blade.php

@@ -4,74 +4,82 @@
     <div moe wide class="">
         <a class="" href="" show start>Create Bill</a>
         <form url="/api/bill/createForNote">
-            <input type="hidden" name="noteUid" value="{{$note->uid}}">
-            <div class="mb-2">
-                <label for="" class="text-secondary text-sm">Effective Date</label>
-                <input type="date" name="effectiveDate" class="form-control form-control-sm" value="{{$note->effective_dateest ? $note->effective_dateest : date('Y-m-d')}}" required>
-            </div>
-            <div class="mb-2">
-                @if($noteRates && count($noteRates))
-                    @if(count($noteRates) === 1)
-                        <input type="hidden" name="code" value="{{$noteRates[0]->code}}">
-                        <p class="mb-2">Service: <b>{{ $noteRates[0]->code }} (${{ $noteRates[0]->amount }}/hr)</b></p>
-                    @else
-                        <select autofocus class="form-control" name="code" onchange="switchNumberOfUnitsByType(this)">
-                            <option value="">-- Select Code --</option>
-                            @foreach($noteRates as $noteRate)
-                                <option data-amount="{{ $noteRate->amount }}" value="{{ $noteRate->code }}">
-                                    {{ $noteRate->code }} (${{ $noteRate->amount }}{{ $noteRate->code === 'Treatment Services' ? '/hr' : '' }})
-                                </option>
-                            @endforeach
-                        </select>
+            <?php $maxMinutes = 30; ?>
+            @if($noteRates && count($noteRates))
+                <input type="hidden" name="noteUid" value="{{$note->uid}}">
+                <div class="mb-2">
+                    <label for="" class="text-secondary text-sm">Effective Date</label>
+                    <input type="date" name="effectiveDate" class="form-control form-control-sm" value="{{$note->effective_dateest ? $note->effective_dateest : date('Y-m-d')}}" required>
+                </div>
+                <div class="mb-2">
+                    @if($noteRates && count($noteRates))
+                        @if(count($noteRates) === 1)
+                            <input type="hidden" name="code" value="{{$noteRates[0]->code}}">
+                            <p class="mb-2">Service: <b>{{ $noteRates[0]->code }} (${{ $noteRates[0]->amount }}/hr)</b></p>
+                        @else
+                            <select autofocus class="form-control" name="code" onchange="switchNumberOfUnitsByType(this)">
+                                <option value="">-- Select Code --</option>
+                                @foreach($noteRates as $noteRate)
+                                    <option data-amount="{{ $noteRate->amount }}" value="{{ $noteRate->code }}">
+                                        {{ $noteRate->code }} (${{ $noteRate->amount }}{{ $noteRate->code === 'Treatment Services' ? '/hr' : '' }})
+                                    </option>
+                                @endforeach
+                            </select>
+                        @endif
                     @endif
-                @endif
-            </div>
+                </div>
 
-            <?php
-                $maxMinutes = 120;
-                if($note->new_or_fu_or_na === 'NEW') {
-                    $maxMinutes = 90;
-                }
-                else if($note->new_or_fu_or_na === 'FU') {
-                    if($note->method === 'VIDEO') {
-                        $maxMinutes = 75;
+                <?php
+                    $maxMinutes = 120;
+                    if($note->new_or_fu_or_na === 'NEW') {
+                        $maxMinutes = 90;
                     }
-                    else if($note->method === 'AUDIO') {
-                        $maxMinutes = 60;
+                    else if($note->new_or_fu_or_na === 'FU') {
+                        if($note->method === 'VIDEO') {
+                            $maxMinutes = 75;
+                        }
+                        else if($note->method === 'AUDIO') {
+                            $maxMinutes = 60;
+                        }
                     }
-                }
-            ?>
+                ?>
 
-            @if($noteRates && count($noteRates) && count($noteRates) === 1)
-                @if(strpos(strtolower($noteRates[0]->code), "treatment services") !== FALSE)
-                    <div class="mb-2">
-                        <select name="numberOfUnits" class="form-control form-control-sm"
-                                onchange="calculateBillAmount(this)">
-                            <option value=""> -- select -- </option>
-                            <?php for ($i = 5; $i <= $maxMinutes; $i+=5) { ?>
-                            <option value="{{ $i/60 }}" {{ $i === 30 ? 'selected' : '' }}>{{ $i }} minutes</option>
-                            <?php } ?>
-                        </select>
-                    </div>
-                    <div class="mb-2" calculated-amount></div>
-                @else
-                    <input type="hidden" name="numberOfUnits" value="1">
+                @if($noteRates && count($noteRates) && count($noteRates) === 1)
+                    @if(strpos(strtolower($noteRates[0]->code), "treatment services") !== FALSE)
+                        <div class="mb-2">
+                            <select name="numberOfUnits" class="form-control form-control-sm"
+                                    onchange="calculateBillAmount(this)">
+                                <option value=""> -- select -- </option>
+                                <?php for ($i = 5; $i <= $maxMinutes; $i+=5) { ?>
+                                <option value="{{ $i/60 }}" {{ $i === 30 ? 'selected' : '' }}>{{ $i }} minutes</option>
+                                <?php } ?>
+                            </select>
+                        </div>
+                        <div class="mb-2" calculated-amount></div>
+                    @else
+                        <input type="hidden" name="numberOfUnits" value="1">
+                    @endif
                 @endif
-            @endif
-            <div class="bill-conditional">
+                <div class="bill-conditional">
 
-            </div>
+                </div>
 
-            @if(@$note && $note->hcpPro->id === $pro->id)
-            <div class="my-3">
-                <input type="checkbox" name="signAndMarkBillingDone" checked>&nbsp;Sign and Mark Billing Done
-            </div>
-            @endif
+                @if(@$note && $note->hcpPro->id === $pro->id)
+                <div class="my-3">
+                    <input type="checkbox" name="signAndMarkBillingDone" checked>&nbsp;Sign and Mark Billing Done
+                </div>
+                @endif
 
-            <div class="">
-                <button class="btn btn-primary btn-sm" submit>Submit</button>
-                <button class="btn btn-default border btn-sm" cancel>Cancel</button>
-            </div>
+                <div class="">
+                    <button class="btn btn-primary btn-sm" submit>Submit</button>
+                    <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                </div>
+            @else
+                <div class="border rounded bg-aliceblue p-2 width-200px">
+                    <i class="fa fa-exclamation-triangle text-warning-mellow mr-1"></i>
+                    Payment rates not yet set for Treatment Services. Please contact admin.
+                </div>
+            @endif
         </form>
         <div class="d-none" hourly-template>
             <div class="mb-2">

+ 42 - 0
resources/views/app/patient/note/_templates-v2-index.blade.php

@@ -0,0 +1,42 @@
+<?php
+$templateIndex = json_decode(file_get_contents(storage_path('templates/index.json')));
+$hasTemplates = false;
+if(isset($templateIndex->{$sectionInternalName})) {
+    $hasTemplates = true;
+    $templateName = '';
+    $defaultTemplateName = '';
+    foreach($templateIndex->{$sectionInternalName} as $k => $templateSet) {
+        if($templateName === '') $templateName = $k;
+        if($templateSet->default) $defaultTemplateName = $k;
+    }
+    if($defaultTemplateName !== '') $templateName = $defaultTemplateName;
+?>
+    <span class="mx-2 text-secondary text-sm d-none if-edit">|</span>
+    <span class="position-relative d-none if-edit">
+        <a href="#" class="note-templates-trigger">Templates</a>
+        <div class="note-template-container">
+            <div class="position-relative w-100">
+                <div class="note-template-output">
+                    <div class="font-weight-bold text-secondary">Result:</div>
+                    <div class="note-template-output-text"></div>
+                </div>
+                <div class="note-template-buttons d-flex align-items-center">
+                    <button class="btn btn-sm btn-default bg-white border text-primary border-primary note-template-apply-trigger">Apply</button>
+                    <button class="btn btn-sm btn-default bg-light border text-secondary border-secondary note-template-close-trigger">Close</button>
+                </div>
+            </div>
+            <div class="p-1 border border-bottom">
+                <select class="form-control form-control-sm note-template-set-chooser" data-section="{{$sectionInternalName}}">
+                    @foreach($templateIndex->{$sectionInternalName} as $k => $templateSet)
+                        <option value="{{$k}}" {{$k === $templateName ? 'selected' : ''}}>{{$templateSet->name}}</option>
+                    @endforeach
+                </select>
+            </div>
+            {{--@include('app/patient/note/_template')--}}
+        </div>
+    </span>
+<?php
+}
+?>
+
+

+ 2131 - 0
resources/views/app/patient/note/dashboard-univ.blade.php

@@ -0,0 +1,2131 @@
+<?php
+/** @var App\Models\Note $note */
+/** @var App\Models\Pro $pro */
+/** @var App\Models\Section $section */
+/** @var $allSections */
+?>
+@extends ('layouts.patient')
+
+@section('inner-content')
+
+    <?php
+    $hasBills = false;
+    if($note->bills->count()) {
+        foreach ($note->bills as $bill) {
+            if(!$bill->is_cancelled) {
+                $hasBills = true;
+                break;
+            }
+        }
+    }
+    ?>
+
+    <div id="note-single-header" class="pb-3 d-flex align-items-start screen-only">
+        <h6 class="my-0 text-secondary d-flex align-items-center w-100">
+            <a href="/patients/view/{{ $patient->uid }}/notes" class="small text-decoration-none mr-3">
+                <i class="fa fa-chevron-left"></i>
+            </a>
+            <div class="mr-auto d-inline-flex align-items-center">
+                <span class="text-dark font-weight-bold">Note (univ *)
+                    <span class="text-secondary font-weight-normal">{{ $note->is_cancelled ? '(CANCELLED)' : '' }}</span>
+                </span>
+                @if($pro->pro_type === 'ADMIN')
+                    <a href="#" class="print-note ml-3 btn btn-sm btn-primary text-white font-weight-bold invisible"><i class="fa fa-print"></i> Print</a>
+                    <?php
+                    $isBad = false;
+                    $isGood = false;
+		            if($note->detail_json) {
+                        $parsed = json_decode($note->detail_json);
+                        $isBad = $parsed && @$parsed->isBad;
+			            $isGood = $parsed && @$parsed->isGood;
+                    }
+                    ?>
+                    @if(!$isBad)
+                        <div moe relative>
+                            <a href="#" start show  class="print-note ml-2 btn btn-sm btn-danger text-white font-weight-bold invisible"><i class="fa fa-exclamation-triangle"></i> Mark as Bad Note</a>
+                            <form url="/api/note/markNoteAsBad" class="mcp-theme-1">
+                                <input type="hidden" name="uid" value="{{$note->uid}}">
+                                <p class="min-width-200px">Mark this note as <b>bad</b>?</p>
+                                <div>
+                                    <button submit class="btn btn-sm btn-success mr-1">Yes</button>
+                                    <button cancel class="btn btn-sm btn-default border">No</button>
+                                </div>
+                            </form>
+                        </div>
+                    @else
+                        <div moe relative>
+                            <a href="#" start show class="print-note ml-2 btn btn-sm btn-info text-white font-weight-bold invisible"><i class="fa fa-undo"></i> Marked as bad! Click to undo.</a>
+                            <form url="/api/note/undoMarkNoteAsBad" class="mcp-theme-1">
+                                <input type="hidden" name="uid" value="{{$note->uid}}">
+                                <p class="min-width-200px">Mark this note as <b>not bad</b>?</p>
+                                <div>
+                                    <button submit class="btn btn-sm btn-success mr-1">Yes</button>
+                                    <button cancel class="btn btn-sm btn-default border">No</button>
+                                </div>
+                            </form>
+                        </div>
+                    @endif
+		            @if(!$isGood)
+                        <div moe relative>
+                            <a href="#" start show  class="print-note ml-2 btn btn-sm btn-success text-white font-weight-bold invisible"><i class="fa fa-check"></i> Mark as Good Note</a>
+                            <form url="/api/note/markNoteAsGood" class="mcp-theme-1">
+                                <input type="hidden" name="uid" value="{{$note->uid}}">
+                                <p class="min-width-200px">Mark this note as <b>good</b>?</p>
+                                <div>
+                                    <button submit class="btn btn-sm btn-success mr-1">Yes</button>
+                                    <button cancel class="btn btn-sm btn-default border">No</button>
+                                </div>
+                            </form>
+                        </div>
+                    @else
+                        <div moe relative>
+                            <a href="#" start show class="print-note ml-2 btn btn-sm btn-info text-white font-weight-bold invisible"><i class="fa fa-undo"></i> Marked as good! Click to undo.</a>
+                            <form url="/api/note/undoMarkNoteAsGood" class="mcp-theme-1">
+                                <input type="hidden" name="uid" value="{{$note->uid}}">
+                                <p class="min-width-200px">Mark this note as <b>not good</b>?</p>
+                                <div>
+                                    <button submit class="btn btn-sm btn-success mr-1">Yes</button>
+                                    <button cancel class="btn btn-sm btn-default border">No</button>
+                                </div>
+                            </form>
+                        </div>
+                    @endif
+                @endif
+            </div>
+            @if($patient->has_mcp_done_onboarding_visit !== 'YES')
+                <div class="ml-auto">
+                    <div moe relative>
+                        <a start show class="font-weight-bold">Mark as Onboarding Visit Note</a>
+                        <form url="/api/client/updateMcpOnboardingVisitInfo" class="mcp-theme-1" right>
+                            <input type="hidden" name="uid" value="{{$patient->uid}}">
+                            <input type="hidden" name="mcpOnboardingVisitNoteUid" value="{{$note->uid}}">
+                            <input type="hidden" name="hasMcpDoneOnboardingVisit" value="YES">
+                            <input type="hidden" name="mcpOnboardingVisitDate" value="{{$note->effective_dateest}}">
+                            <p class="min-width-200px">Mark this patient's onboarding as completed using this note?</p>
+                            <div>
+                                <button submit class="btn btn-sm btn-success mr-1">Yes</button>
+                                <button cancel class="btn btn-sm btn-default border">No</button>
+                            </div>
+                        </form>
+                    </div>
+
+                </div>
+            @endif
+        </h6>
+    </div>
+
+    <div class="card mb-0 {{ $note->is_cancelled ? 'cancelled-item' : '' }}">
+        <div class="card-header d-flex align-items-start px-3 py-2 border-bottom" id="note-card-header">
+            <div class="pr-2">
+                {{$note->title}}
+                @if(!$note->is_signed_by_hcp || $pro->pro_type === 'ADMIN')
+                <div moe>
+                    <a href="" show start><i class="fa fa-edit"></i></a>
+                    <form url="/api/note/putTitle">
+                        <input type="hidden" name="uid" value="{{$note->uid}}">
+                        <div class="mb-2">
+                            <input type="text" name="title" value="{{$note->title}}" class="form-control form-control-sm"
+                                   placeholder="Title">
+                        </div>
+                        <div class="form-group mb-0">
+                            <button class="btn btn-primary btn-sm" submit>Submit</button>
+                            <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                        </div>
+                    </form>
+                </div>
+                @endif
+            </div>
+            <div class="px-2 border-left border-right">
+                <div class="d-flex">
+                    <span class="mr-2">{{friendly_date_time($note->effective_dateest, false, '')}}</span>
+                    @if(!$note->is_signed_by_hcp || $pro->pro_type === 'ADMIN')
+                    <span moe class="ml-auto">
+                        <a href="" show start><i class="fa fa-calendar"></i></a>
+                        <form url="/api/note/putEffectiveDateEST">
+                            <input type="hidden" name="uid" value="{{$note->uid}}">
+                            <div class="mb-2">
+                                <label for="" class="text-secondary text-sm">Effective date EST</label>
+                                <input type="date" name="effectiveDateEST" value="{{$note->effective_dateest}}" class="form-control form-control-sm">
+                            </div>
+                            <div class="mb-0">
+                                <button class="btn btn-primary btn-sm" submit>Submit</button>
+                                <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                            </div>
+                        </form>
+                    </span>
+                    @endif
+                </div>
+            </div>
+
+            {{--<div class="px-2 border-left border-right">
+                <div class="d-flex">
+                    <span class="mr-2">{{friendly_time($note->effective_time, '')}}</span>
+                    @if(!$note->is_signed_by_hcp)
+                        <span moe class="ml-auto">
+                            <a href="" show start><i class="fa fa-clock"></i></a>
+                            <form url="/api/note/putEffectiveTime">
+                                <input type="hidden" name="uid" value="{{$note->uid}}">
+                                <div class="mb-2">
+                                    <label for="" class="text-secondary text-sm">Effective time </label>
+                                    <input type="time" name="effectiveTime" value="{{ date("H:i", strtotime($note->effective_time)) }}" class="form-control form-control-sm">
+                                </div>
+                                <div class="mb-0">
+                                    <button class="btn btn-primary btn-sm" submit>Submit</button>
+                                    <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                                </div>
+                            </form>
+                        </span>
+                    @endif
+                </div>
+            </div>--}}
+
+            <div class="px-2 border-right">
+                <div class="d-flex">
+                    <span class="mr-2"><span class="text-secondary">HCP:</span> {{$note->hcpPro->name_display}}</span>
+                    @if(!$note->is_signed_by_hcp || $pro->pro_type === 'ADMIN')
+                    <div moe class="ml-auto">
+                        <a href="" show start><i class="fa fa-edit"></i></a>
+                        <form url="/api/note/putHcp">
+                            <input type="hidden" name="uid" value="{{$note->uid}}">
+                            <div class="mb-2">
+                                <select provider-search data-pro-uid="{{ @$note->hcpPro->uid }}"
+                                        name="hcpProUid" class="form-control form-control-sm">
+                                    <option value="">-- Select HCP Pro --</option>
+                                </select>
+                            </div>
+                            <div class="mb-0">
+                                <button class="btn btn-primary btn-sm" submit>Submit</button>
+                                <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                            </div>
+                        </form>
+                    </div>
+                    @endif
+                </div>
+            </div>
+
+
+            @if($performer->pro->pro_type == 'ADMIN' || ($note->allyPro && $note->allyPro->uid === $performer->pro->uid))
+                <span class="px-2 border-right d-flex">
+                    @if($note->allyPro)
+                        <span class="mr-2"><span class="text-secondary">NA:</span>  {{$note->allyPro->name_first}} {{$note->allyPro->name_last}}</span>
+                        @if($performer->pro->pro_type == 'ADMIN')
+                            <span class="d-inline-block" moe>
+                                <a class="text-danger" href="" show start>
+                                    <i class="fa fa-times"></i>
+                                </a>
+                                <form url="/api/note/removeNa">
+                                    <input type="hidden" name="uid" value="{{$note->uid}}">
+                                    <p>Remove NA?</p>
+                                    <div class="mb-0">
+                                        <button class="btn btn-success btn-sm" submit>Submit</button>
+                                        <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                                    </div>
+                                </form>
+                            </span>
+                        @endif
+                    @else
+                        <span class="mr-2"><span class="text-secondary">NA:</span> - </span>
+                        <span class="d-block" moe>
+                            <a class="" href="" show start>
+                                <i class="fa fa-edit"></i>
+                            </a>
+                            <form url="/api/note/putNa">
+                                <input type="hidden" name="uid" value="{{$note->uid}}">
+                                <div class="form-group">
+                                    <label for="" class="control-label">NA</label>
+                                    <select provider-search
+                                            name="naProUid" class="form-control form-control-sm">
+                                        <option value="">-- Select Ally Pro --</option>
+                                    </select>
+                                </div>
+                                <div class="mb-0">
+                                    <button class="btn btn-success btn-sm" submit>Submit</button>
+                                    <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                                </div>
+                            </form>
+                        </span>
+                    @endif
+
+                </span>
+            @endif
+
+
+            <div class="px-2 border-right">
+                <div class="d-flex">
+                    <span class="mr-2"><span class="text-secondary">Type:</span> {{$note->new_or_fu_or_na ? ($note->new_or_fu_or_na === 'NEW' ? 'New Patient' : $note->new_or_fu_or_na) : '-'}}</span>
+                    @if(!$note->is_signed_by_hcp || $pro->pro_type === 'ADMIN')
+                        <div moe class="ml-auto">
+                            <a href="" show start><i class="fa fa-edit"></i></a>
+                            <form url="/api/note/updateNewOrFuOrNa">
+                                <input type="hidden" name="uid" value="{{$note->uid}}">
+                                <div class="mb-2">
+                                    <select name="newOrFuOrNa" class="form-control form-control-sm" required>
+                                        <option value="">-- select --</option>
+                                        <option value="NEW" {{ $note->new_or_fu_or_na === "NEW" ? "selected" : "" }}>New</option>
+                                        <option value="FU" {{ $note->new_or_fu_or_na === "FU" ? "selected" : "" }}>Follow-up</option>
+                                        <option value="NA" {{ $note->new_or_fu_or_na === "NA" ? "selected" : "" }}>N/A</option>
+                                    </select>
+                                </div>
+                                <div class="mb-0">
+                                    <button class="btn btn-primary btn-sm" submit>Submit</button>
+                                    <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                                </div>
+                            </form>
+                        </div>
+                    @endif
+                </div>
+            </div>
+
+            <div class="px-2">
+                <div class="d-flex">
+                    <span class="mr-2"><span class="text-secondary">Method:</span> {{$note->method ? $note->method : '-'}}</span>
+                    @if(!$note->is_signed_by_hcp || $pro->pro_type === 'ADMIN')
+                        <div moe class="ml-auto">
+                            <a href="" show start><i class="fa fa-edit"></i></a>
+                            <form url="/api/note/updateMethod">
+                                <input type="hidden" name="uid" value="{{$note->uid}}">
+                                <div class="mb-2">
+                                    <select name="method" class="form-control form-control-sm note-method-select" required>
+                                        <option value="AUDIO" {{ $note->method === "AUDIO" ? "selected" : "" }}>Audio</option>
+                                        <option value="VIDEO" {{ $note->method === "VIDEO" ? "selected" : "" }}>Video</option>
+                                        <option value="IN_CLINIC" {{ $note->method === "IN_CLINIC" ? "selected" : "" }}>In-Clinic</option>
+                                        <option value="HOUSE_CALL" {{ $note->method === "HOUSE_CALL" ? "selected" : "" }}>House Call</option>
+                                    </select>
+                                </div>
+                                <div class="form-group if-in-clinic">
+                                    <label for="" class="text-secondary text-sm mb-1">Location</label>
+                                    <select name="hcpCompanyLocationUid" class="form-control">
+                                        <option value=""></option>
+                                        @foreach($pro->companyLocations() as $location)
+                                            <option value="{{$location->uid}}" {{$location->id === $note->hcp_company_location_id ? 'selected' : ''}}>{{$location->line1}} {{$location->city}}</option>
+                                        @endforeach
+                                    </select>
+                                </div>
+                                <div class="mb-0">
+                                    <button class="btn btn-primary btn-sm" submit>Submit</button>
+                                    <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                                </div>
+                            </form>
+                        </div>
+                    @endif
+                </div>
+            </div>
+
+            <div class="ml-auto d-flex align-items-start">
+                <div class="">
+                    <div>
+                        @if($note->is_signed_by_hcp)
+                            <span class="text-secondary">
+                        <i class="fa fa-check"></i>
+                        Note Signed
+                        @if($pro->pro_type == 'ADMIN')
+                        <span moe class="ml-2 d-none">
+                            <a class="" href="" show start>Undo sign?</a>
+                            <form url="/api/note/adminUndoSignAsHcp" right>
+                                <input type="hidden" name="uid" value="{{$note->uid}}">
+                                <p>Undo sign?</p>
+                                <div class="mb-0">
+                                    <button class="btn btn-success btn-sm" submit>Submit</button>
+                                    <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                                </div>
+                            </form>
+                        </span>
+                        @endif
+                    </span>
+                        @else
+                            <div moe
+                                 class="{{ $note->hcp_pro_id !== $pro->id ? 'moe-disabled' : '' }}"
+                                 title="{{ $note->hcp_pro_id !== $pro->id ? 'Only the note\'s HCP can sign' : '' }}">
+                                <a class="" href="" show start>Sign Note As HCP</a>
+                                <form url="/api/note/signAsHcp" right>
+                                    <input type="hidden" name="uid" value="{{$note->uid}}">
+                                    <p>Sign this note as HCP?</p>
+                                    <div class="mb-0">
+                                        <button class="btn btn-success btn-sm" submit>Sign</button>
+                                        <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                                    </div>
+                                </form>
+                            </div>
+                        @endif
+                    </div>
+                </div>
+                @if($note->allyPro)
+                <div class="mx-4">
+                    <div>
+                        @if($note->is_signed_by_ally)
+                            <span class="text-secondary">
+                        <i class="fa fa-check"></i>
+                        Note Signed By NA
+                    </span>
+                        @else
+                            <div moe
+                                 class="{{ $note->ally_pro_id !== $pro->id ? 'moe-disabled' : '' }}"
+                                 title="{{ $note->ally_pro_id !== $pro->id ? 'Only the note\'s Ally can sign' : '' }}">
+                                <a class="" href="" show start>Sign Note As NA</a>
+                                <form url="/api/note/signAsAlly" right>
+                                    <input type="hidden" name="uid" value="{{$note->uid}}">
+                                    <p>Sign this NA?</p>
+                                    <div class="mb-0">
+                                        <button class="btn btn-success btn-sm" submit>Sign</button>
+                                        <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                                    </div>
+                                </form>
+                            </div>
+                        @endif
+                    </div>
+                </div>
+                @endif
+                @if($note->is_cancelled || (!$note->is_cancelled && !$note->is_signed_by_hcp))
+                <div class="ml-2 pl-2 border-left">
+                    <div class="d-flex justify-content-end">
+                        @if(!$note->is_cancelled)
+                        <div moe relatve
+                             class="{{ $hasBills ? 'moe-disabled' : '' }}"
+                             title="{{ $hasBills ? 'Cannot cancel note since it has un-cancelled bills in it' : '' }}">
+                            <a class="text-danger" href="" show start>Cancel</a>
+                            <form url="/api/note/cancel" right>
+                                <input type="hidden" name="uid" value="{{$note->uid}}">
+                                <p class="small mb-2">Are you sure you want to cancel this note?</p>
+                                <div class="mb-2">
+                                    <textarea name="memo" id="" cols="30" rows="5" placeholder="Memo" class="memo-textarea form-control form-control-sm"></textarea>
+                                </div>
+                                <div class="d-flex align-items-center">
+                                    <button class="btn btn-sm btn-danger mr-2" submit>Yes</button>
+                                    <button class="btn btn-sm btn-default mr-2 border" cancel>No</button>
+                                </div>
+                            </form>
+                        </div>
+                        @else
+                            <span class="text-secondary font-weight-bold">CANCELLED</span>
+                        @endif
+                    </div>
+                </div>
+                @endif
+
+            </div>
+        </div>
+        <div class="card-body p-0">
+            <div class="note-container">
+                <div class="note-lhs-tree" id="note-lhs-tree">
+                    <?php
+                    $previousHeading = null;
+                    $sectionTemplates = $note->noteTemplate->sectionTemplatesRaw();
+                    ?>
+                    @foreach($sectionTemplates as $sectionTemplate)
+                        <?php
+                        if($sectionTemplate->heading !== $previousHeading) {
+                            if(!empty($previousHeading)) {
+                                echo '</div></div>'; // <!-- end the previous parent section -->
+                            }
+                            if(!empty($sectionTemplate->heading)) {
+                                echo '<div class="note-tree-node note-tree-heading">' .
+                                        '<a class="">' . $sectionTemplate->heading . '</a>' .
+                                        '<div class="note-tree-children">'; // <!-- open new node -->
+                            }
+                            $previousHeading = $sectionTemplate->heading;
+                        }
+                        echo '<div class="note-tree-node">' .
+                            '<a native target="_top" data-section-template-name="' . $sectionTemplate->internal_name . '" href="#" >' . $sectionTemplate->title . '</a>' .
+                            '</div>';
+                        ?>
+                    @endforeach
+                    <?php
+                    if(!empty($previousHeading)) {
+                        echo '</div></div>'; // <!-- close any open parent section -->
+                    }
+                    ?>
+                </div>
+                <div class="note-rhs-content">
+                    <div>
+                        <div class="">
+                            <div>
+                                <?php
+                                $shortCutsObject = [];
+                                foreach ($pro->allShortcuts() as $shortcut) {
+
+                                    // %replaceables%
+                                    $shortcut->text = str_replace("%AGE%", $patient->age_in_years, $shortcut->text);
+                                    $shortcut->text = str_replace("%GENDER%", $patient->sex, $shortcut->text);
+                                    $shortcut->text = str_replace("%NAME%", $patient->displayName(), $shortcut->text);
+
+                                    $shortCutsObject[] = [
+                                        "name" => $shortcut->shortcut,
+                                        "value" => $shortcut->text
+                                    ];
+                                }
+                                ?>
+                                <script>window.userShortcuts = <?= json_encode($shortCutsObject); ?>;</script>
+                                <?php
+                                $shortcuts = "";
+                                $latestSectionTS = 0;
+                                ?>
+                                <div class="{{ $note->is_signed_by_hcp ? 'note-signed-by-hcp' : '' }}">
+                                    @include('app.patient.note.note-section-list')
+                                </div>
+                            </div>
+                        </div>
+
+                        <span class="d-none latest-section-ts">{{ $latestSectionTS }}</span>
+
+                        <div class="p-3 border-bottom">
+                            <div class="">
+                                <div class="d-flex align-items-center mb-2">
+                                    <p class="font-weight-bold text-secondary m-0 font-size-14">ERx/Orders Summary</p>
+                                    <span class="mx-2 text-secondary screen-only">|</span>
+                                    <a href="/patients/view/{{$patient->uid}}/tickets/erx/create?popupmode=1&note-uid={{$note->uid}}"
+                                       native target="_blank"
+                                       class="ticket-popup-trigger note-dashboard-action d-block text-nowrap screen-only">
+                                        + ERx
+                                    </a>
+                                    <span class="mx-2 text-secondary screen-only">|</span>
+                                    <a href="/patients/view/{{$patient->uid}}/tickets/lab/create?popupmode=1&note-uid={{$note->uid}}"
+                                       native target="_blank"
+                                       class="ticket-popup-trigger note-dashboard-action d-block text-nowrap screen-only">
+                                        + Lab
+                                    </a>
+                                    <span class="mx-2 text-secondary screen-only">|</span>
+                                    <a href="/patients/view/{{$patient->uid}}/tickets/imaging/create?popupmode=1&note-uid={{$note->uid}}"
+                                       native target="_blank"
+                                       class="ticket-popup-trigger note-dashboard-action d-block text-nowrap screen-only">
+                                        + Imaging
+                                    </a>
+                                    <span class="mx-2 text-secondary screen-only">|</span>
+                                    <a href="/patients/view/{{$patient->uid}}/tickets/other/create?popupmode=1&note-uid={{$note->uid}}"
+                                       native target="_blank"
+                                       class="ticket-popup-trigger note-dashboard-action d-block text-nowrap screen-only">
+                                        + Other
+                                    </a>
+                                </div>
+
+                                <div class="p-3 border">
+
+                                    <p class="font-weight-bold text-secondary mb-2 mr-2">Associated with this note</p>
+                                    <div>
+                                        @if($ticketsOnNote && count($ticketsOnNote))
+                                            <table class="table table-sm table-bordered mb-0">
+                                                <thead>
+                                                <tr class="bg-light">
+                                                    <th class="px-2 text-secondary border-bottom-0 width-30px">Created</th>
+                                                    <th class="px-2 text-secondary border-bottom-0 width-30px">Type</th>
+                                                    <th class="px-2 text-secondary border-bottom-0 width-30px">Pro</th>
+                                                    <th class="px-2 text-secondary border-bottom-0 width-30px">View</th>
+                                                    <th class="px-2 text-secondary border-bottom-0 width-30px">Status</th>
+                                                    <th class="px-2 text-secondary border-bottom-0">Detail</th>
+                                                </tr>
+                                                </thead>
+                                                <tbody>
+                                                @foreach($ticketsOnNote as $ticket)
+                                                    <?php $data = json_decode($ticket->data); ?>
+                                                    @if($ticket->category === 'erx' || $ticket->category === 'lab' || $ticket->category === 'imaging')
+                                                        <tr class="{{$ticket->is_open ? '' : 'bg-light on-hover-opaque'}}">
+                                                            <td class="px-2 text-nowrap">
+                                                                {{friendly_time($ticket->created_at)}}
+                                                            </td>
+                                                            <td class="px-2 text-nowrap">
+                                                                {{$ticket->category}}
+                                                            </td>
+                                                            <td class="px-2 text-nowrap">
+                                                                @if($ticket->orderingPro)
+                                                                    @if($ticket->orderingPro->id !== $pro->id)
+                                                                        <b>{{$ticket->orderingPro->displayName()}}</b>
+                                                                    @else
+                                                                        You
+                                                                    @endif
+                                                                @else
+                                                                    -
+                                                                @endif
+                                                            </td>
+                                                            <td class="px-2 text-nowrap">
+                                                                <div class="d-flex align-items-center flex-nowrap">
+                                                                    <a href="/patients/view/{{$ticket->patient->uid}}/tickets/{{$ticket->category}}/{{$ticket->uid}}?popupmode=1"
+                                                                       native target="_blank"
+                                                                       class="ticket-popup-trigger note-dashboard-action d-block text-nowrap mr-3">
+                                                                        View
+                                                                    </a>
+                                                                </div>
+                                                            </td>
+                                                            <td class="px-2 text-nowrap">
+                                                                {{$ticket->is_open ? 'Open' : 'Closed'}}
+                                                            </td>
+                                                            <td class="px-2">
+                                                                @if($ticket->category === 'erx')
+                                                                    <div class="font-size-13 mb-1">{{$data->medication}}</div>
+                                                                    <div class="d-flex align-items-center flex-wrap text-secondary">
+                                                                        @if($data->strength)
+                                                                            <span class="d-inline-flex align-items-center">
+                                                            <span class="mx-2 text-secondary">•</span>
+                                                            <span>{{$data->strength}}</span>
+                                                        </span>
+                                                                        @endif
+                                                                        @if($data->route)
+                                                                            <span class="d-inline-flex align-items-center">
+                                                            <span class="mx-2 text-secondary">•</span>
+                                                            <span>{{$data->route}}</span>
+                                                        </span>
+                                                                        @endif
+                                                                        @if($data->frequency)
+                                                                            <span class="d-inline-flex align-items-center">
+                                                            <span class="mx-2 text-secondary">•</span>
+                                                            <span>{{$data->frequency}}</span>
+                                                        </span>
+                                                                        @endif
+                                                                        @if($data->dispense)
+                                                                            <span class="d-inline-flex align-items-center">
+                                                            <span class="mx-2 text-secondary">•</span>
+                                                            <span>Dispense:</span> {{$data->dispense}}
+                                                        </span>
+                                                                        @endif
+                                                                        @if($data->frequency)
+                                                                            <span class="d-inline-flex align-items-center">
+                                                            <span class="mx-2 text-secondary">•</span>
+                                                            <span><span>Refills:</span> {{$data->refills}}</span>
+                                                        </span>
+                                                                        @endif
+                                                                        @if($data->dispense)
+                                                                            <span class="d-inline-flex align-items-center">
+                                                            <span class="mx-2 text-secondary">•</span>
+                                                            <span><span>Purpose:</span> {{$data->purpose}}</span>
+                                                        </span>
+                                                                        @endif
+                                                                    </div>
+                                                                @endif
+                                                                @if($ticket->category === 'lab' || $ticket->category === 'imaging')
+                                                                    @if(@$data->tests && is_array($data->tests))
+                                                                        <div>
+                                                                            <span class="text-secondary">Tests:</span>
+                                                                            {{implode(", ", $data->tests)}}
+                                                                        </div>
+                                                                    @endif
+                                                                    @if(@$data->icds && is_array($data->icds))
+                                                                        <div>
+                                                                            <span class="text-secondary">ICDs:</span>
+                                                                            {{implode(", ", $data->icds)}}
+                                                                        </div>
+                                                                    @endif
+                                                                @endif
+                                                            </td>
+                                                        </tr>
+                                                    @endif
+                                                @endforeach
+                                                </tbody>
+                                            </table>
+                                        @else
+                                            <div class="text-secondary">None</div>
+                                        @endif
+                                    </div>
+
+                                    <hr class="my-2">
+
+                                    <p class="font-weight-bold text-secondary mb-2 mr-2">Others open as of {{friendlier_date(date('Y-m-d'))}}</p>
+                                    @if($otherOpenTickets && count($otherOpenTickets))
+                                        <table class="table table-sm table-bordered mb-0">
+                                            <thead>
+                                            <tr class="bg-light">
+                                                <th class="px-2 text-secondary border-bottom-0 width-30px">Created</th>
+                                                <th class="px-2 text-secondary border-bottom-0 width-30px">Type</th>
+                                                <th class="px-2 text-secondary border-bottom-0 width-30px">Pro</th>
+                                                <th class="px-2 text-secondary border-bottom-0 width-30px">View</th>
+                                                <th class="px-2 text-secondary border-bottom-0 width-30px">Status</th>
+                                                <th class="px-2 text-secondary border-bottom-0">Detail</th>
+                                            </tr>
+                                            </thead>
+                                            <tbody>
+                                            @foreach($otherOpenTickets as $ticket)
+                                                <?php $data = json_decode($ticket->data); ?>
+                                                @if($ticket->category === 'erx' || $ticket->category === 'lab' || $ticket->category === 'imaging' || $ticket->category === 'other')
+                                                    <tr class="{{$ticket->is_open ? '' : 'bg-light on-hover-opaque'}}">
+                                                        <td class="px-2 text-nowrap">
+                                                            {{friendly_time($ticket->created_at)}}
+                                                        </td>
+                                                        <td class="px-2 text-nowrap">
+                                                            {{$ticket->category}}
+                                                        </td>
+                                                        <td class="px-2 text-nowrap">
+                                                            @if($ticket->orderingPro)
+                                                                @if($ticket->orderingPro->id !== $pro->id)
+                                                                    <b>{{$ticket->orderingPro->displayName()}}</b>
+                                                                @else
+                                                                    You
+                                                                @endif
+                                                            @else
+                                                                -
+                                                            @endif
+                                                        </td>
+                                                        <td class="px-2 text-nowrap">
+                                                            <div class="d-flex align-items-center flex-nowrap">
+                                                                <a href="/patients/view/{{$ticket->patient->uid}}/tickets/{{$ticket->category}}/{{$ticket->uid}}?popupmode=1"
+                                                                   native target="_blank"
+                                                                   class="ticket-popup-trigger note-dashboard-action d-block text-nowrap mr-3">
+                                                                    View
+                                                                </a>
+                                                            </div>
+                                                        </td>
+                                                        <td class="px-2 text-nowrap">
+                                                            {{$ticket->is_open ? 'Open' : 'Closed'}}
+                                                        </td>
+                                                        <td class="px-2">
+                                                            @if($ticket->category === 'erx')
+                                                                <div class="font-size-13 mb-1">{{$data->medication}}</div>
+                                                                <div class="d-flex align-items-center flex-wrap text-secondary">
+                                                                    @if($data->strength)
+                                                                        <span class="d-inline-flex align-items-center">
+                                                                            <span class="mx-2 text-secondary">•</span>
+                                                                            <span>{{$data->strength}}</span>
+                                                                        </span>
+                                                                    @endif
+                                                                    @if($data->route)
+                                                                        <span class="d-inline-flex align-items-center">
+                                                                            <span class="mx-2 text-secondary">•</span>
+                                                                            <span>{{$data->route}}</span>
+                                                                        </span>
+                                                                    @endif
+                                                                    @if($data->frequency)
+                                                                        <span class="d-inline-flex align-items-center">
+                                                                            <span class="mx-2 text-secondary">•</span>
+                                                                            <span>{{$data->frequency}}</span>
+                                                                        </span>
+                                                                    @endif
+                                                                    @if($data->dispense)
+                                                                        <span class="d-inline-flex align-items-center">
+                                                                            <span class="mx-2 text-secondary">•</span>
+                                                                            <span>Dispense:</span> {{$data->dispense}}
+                                                                        </span>
+                                                                    @endif
+                                                                    @if($data->frequency)
+                                                                        <span class="d-inline-flex align-items-center">
+                                                                            <span class="mx-2 text-secondary">•</span>
+                                                                            <span><span>Refills:</span> {{$data->refills}}</span>
+                                                                        </span>
+                                                                    @endif
+                                                                    @if($data->dispense)
+                                                                        <span class="d-inline-flex align-items-center">
+                                                                            <span class="mx-2 text-secondary">•</span>
+                                                                            <span><span>Purpose:</span> {{$data->purpose}}</span>
+                                                                        </span>
+                                                                    @endif
+                                                                </div>
+                                                            @endif
+                                                            @if($ticket->category === 'lab' || $ticket->category === 'imaging')
+                                                                @if(@$data->tests && is_array($data->tests))
+                                                                    <div>
+                                                                        <span class="text-secondary">Tests:</span>
+                                                                        {{implode(", ", $data->tests)}}
+                                                                    </div>
+                                                                @endif
+                                                                @if(@$data->icds && is_array($data->icds))
+                                                                    <div>
+                                                                        <span class="text-secondary">ICDs:</span>
+                                                                        {{implode(", ", $data->icds)}}
+                                                                    </div>
+                                                                @endif
+                                                            @endif
+                                                            @if($ticket->category === 'other')
+                                                                <div>
+                                                                    {{$data->title}}
+                                                                </div>
+                                                            @endif
+                                                        </td>
+                                                    </tr>
+                                                @endif
+                                            @endforeach
+                                            </tbody>
+                                        </table>
+                                    @else
+                                        <div class="text-secondary">None</div>
+                                    @endif
+
+                                </div>
+
+                            </div>
+                        </div>
+
+                        <div class="p-3 border-bottom">
+                            <div class="">
+                                <div class="d-flex align-items-center mb-2">
+                                    <p class="font-weight-bold text-secondary m-0 font-size-14">Supply Orders Summary</p>
+                                    <span class="mx-2 text-secondary screen-only">|</span>
+                                    <a native target="_blank"
+                                       class="screen-only"
+                                       open-in-stag-popup
+                                       update-parent
+                                       mc-initer="patient-supply-orders"
+                                       title="{{$patient->displayName()}} - Supply Orders"
+                                       href="/patients/view/{{$patient->uid}}/supply-orders?popupmode=1&note-uid={{$note->uid}}&filter=active">
+                                        Manage Supply Orders
+                                    </a>
+                                </div>
+
+                                <div class="p-3 border">
+
+                                    <p class="font-weight-bold text-secondary mb-2 mr-2">Associated with this note</p>
+                                    <div>
+                                        @if($supplyOrdersOnNote && count($supplyOrdersOnNote))
+                                            <table class="table table-sm table-bordered mb-0">
+                                                <thead>
+                                                <tr class="bg-light">
+                                                    <th class="px-2 text-nowrap text-secondary border-bottom-0"><div class="text-ellipsis">Title</div></th>
+                                                    <th class="px-2 text-nowrap text-secondary border-bottom-0"><div class="text-ellipsis">Reason</div></th>
+                                                    <th class="px-2 text-nowrap text-secondary border-bottom-0"><div class="text-ellipsis">Created At</div></th>
+                                                    <th class="px-2 text-nowrap text-secondary border-bottom-0"><div class="text-ellipsis">Pro Signed?</div></th>
+                                                    <th class="px-2 text-nowrap text-secondary border-bottom-0"><div class="text-ellipsis">Cancelled?</div></th>
+                                                    <th class="px-2 text-nowrap text-secondary border-bottom-0"><div class="text-ellipsis">Shipment</div></th>
+                                                </tr>
+                                                </thead>
+                                                <tbody>
+                                                @foreach($supplyOrdersOnNote as $iSupplyOrder)
+                                                    <tr class="">
+                                                        <td class="px-2">
+                                                            {{ $iSupplyOrder->product->title }}
+                                                        </td>
+                                                        <td class="px-2">{{ $iSupplyOrder->reason }}</td>
+                                                        <td class="px-2">{{ friendlier_date_time($iSupplyOrder->created_at) }}</td>
+                                                        <td class="px-2">{{ $iSupplyOrder->is_signed_by_pro ? $iSupplyOrder->signedPro->displayName() : '-' }}</td>
+                                                        <td class="px-2">{{ $iSupplyOrder->is_cancelled ? 'Yes' : 'No' }}</td>
+                                                        <td class="px-2">
+                                                            @if($iSupplyOrder->shipment_id)
+                                                                <i class="fa fa-building"></i>
+                                                                {{$iSupplyOrder->shipment->status ? $iSupplyOrder->shipment->status : 'CREATED'}}
+                                                            @elseif($iSupplyOrder->is_cleared_for_shipment)
+                                                                <span class="text-info">
+                                                            <i class="fa fa-user-nurse"></i>
+                                                            Cleared for shipment
+                                                        </span>
+                                                            @else
+                                                                <span class="text-warning-mellow">
+                                                            <i class="fa fa-user-nurse"></i>
+                                                            Not cleared for shipment
+                                                        </span>
+                                                            @endif
+                                                        </td>
+                                                    </tr>
+                                                @endforeach
+                                                </tbody>
+                                            </table>
+                                        @else
+                                            <div class="text-secondary">None</div>
+                                        @endif
+                                    </div>
+
+                                    <hr class="my-2">
+
+                                    <p class="font-weight-bold text-secondary mb-2 mr-2">Others as of {{friendlier_date(date('Y-m-d'))}}</p>
+                                    @if($otherOpenSupplyOrders && count($otherOpenSupplyOrders))
+                                        <table class="table table-sm table-bordered mb-0">
+                                            <thead>
+                                            <tr class="bg-light">
+                                                <th class="px-2 text-nowrap text-secondary border-bottom-0"><div class="text-ellipsis">Title</div></th>
+                                                <th class="px-2 text-nowrap text-secondary border-bottom-0"><div class="text-ellipsis">Reason</div></th>
+                                                <th class="px-2 text-nowrap text-secondary border-bottom-0"><div class="text-ellipsis">Created At</div></th>
+                                                <th class="px-2 text-nowrap text-secondary border-bottom-0"><div class="text-ellipsis">Pro Signed?</div></th>
+                                                <th class="px-2 text-nowrap text-secondary border-bottom-0"><div class="text-ellipsis">Cancelled?</div></th>
+                                                <th class="px-2 text-nowrap text-secondary border-bottom-0"><div class="text-ellipsis">Shipment</div></th>
+                                            </tr>
+                                            </thead>
+                                            <tbody>
+                                            @foreach($otherOpenSupplyOrders as $iSupplyOrder)
+                                                <tr class="">
+                                                    <td class="px-2">
+                                                        {{ $iSupplyOrder->product->title }}
+                                                    </td>
+                                                    <td class="px-2">{{ $iSupplyOrder->reason }}</td>
+                                                    <td class="px-2">{{ friendlier_date_time($iSupplyOrder->created_at) }}</td>
+                                                    <td class="px-2">{{ $iSupplyOrder->is_signed_by_pro ? $iSupplyOrder->signedPro->displayName() : '-' }}</td>
+                                                    <td class="px-2">{{ $iSupplyOrder->is_cancelled ? 'Yes' : 'No' }}</td>
+                                                    <td class="px-2">
+                                                        @if($iSupplyOrder->shipment_id)
+                                                            <i class="fa fa-building"></i>
+                                                            {{$iSupplyOrder->shipment->status ? $iSupplyOrder->shipment->status : 'CREATED'}}
+                                                        @elseif($iSupplyOrder->is_cleared_for_shipment)
+                                                            <span class="text-info">
+                                                            <i class="fa fa-user-nurse"></i>
+                                                            Cleared for shipment
+                                                        </span>
+                                                        @else
+                                                            <span class="text-warning-mellow">
+                                                            <i class="fa fa-user-nurse"></i>
+                                                            Not cleared for shipment
+                                                        </span>
+                                                        @endif
+                                                    </td>
+                                                </tr>
+                                            @endforeach
+                                            </tbody>
+                                        </table>
+                                    @else
+                                        <div class="text-secondary">None</div>
+                                    @endif
+
+                                </div>
+
+                            </div>
+                        </div>
+
+                        <div class="p-3 border-bottom">
+                            <div class="">
+                                <div class="d-flex align-items-center mb-2">
+                                    <p class="font-weight-bold text-secondary m-0 mr-2">ICDs</p>
+                                    @include('app/patient/note/_create-note-reason')
+                                </div>
+                                <div class="d-flex align-items-start flex-wrap">
+                                    @if(count($note->reasons))
+                                        @foreach ($note->reasons as $reason)
+                                            <span class="badge badge-info p-2 mb-2 mr-2">
+                                    {{ $reason->description}} ({{ $reason->code }})
+                                </span>
+                                        @endforeach
+                                    @else
+                                        <div class="alert alert-info">No note reasons</div>
+                                    @endif
+                                </div>
+                            </div>
+                        </div>
+                        @if($pro->pro_type === 'ADMIN')
+                            <div class="p-3 border-bottom screen-only">
+                                <div>
+                                    <h2 class="font-weight-bold text-secondary">Bills & Claims Summary</h2>
+                                    <div class="d-flex justify-content-center align-items-start">
+                                        <table class="w-25 flex-grow-1 table-bordered table-condensed table-sm table-striped">
+                                            <tbody>
+                                            <tr>
+                                                <td class="text-secondary">Bill Total Exp.</td>
+                                                <td>${{friendly_money($note->bill_total_expected)}}</td>
+                                            </tr>
+                                            <tr>
+                                                <td class="text-secondary">Is Billing Closed</td>
+                                                <td>{{$note->is_bill_closed ? 'Yes' : 'No'}}</td>
+                                            </tr>
+                                            <tr>
+                                                <td class="text-secondary">Bill Summary</td>
+                                                <td>{{$note->bill_summary ? $note->bill_summary : '-'}}</td>
+                                            </tr>
+                                            <tr>
+                                                <td class="text-secondary">Bill Total Paid</td>
+                                                <td>${{friendly_money($note->bill_total_paid)}}</td>
+                                            </tr>
+                                            <tr>
+                                                <td class="text-secondary">Billing Closed At</td>
+                                                <td>{{friendlier_date_time($note->bill_closed_at)}}</td>
+                                            </tr>
+                                            </tbody>
+                                        </table>
+                                        <table class="w-25 flex-grow-1 table-bordered table-condensed table-sm table-striped ml-2">
+                                            <tbody>
+                                            <tr>
+                                                <td class="text-secondary">Claim Total Exp.</td>
+                                                <td>${{friendly_money($note->claim_total_expected)}}</td>
+                                            </tr>
+                                            <tr>
+                                                <td class="text-secondary">Is Claiming Closed</td>
+                                                <td>{{$note->is_claim_closed ? 'Yes' : 'No'}}</td>
+                                            </tr>
+                                            <tr>
+                                                <td class="text-secondary">Claim Summary</td>
+                                                <td>{{$note->claim_summary ? $note->claim_summary : '-'}}</td>
+                                            </tr>
+                                            <tr>
+                                                <td class="text-secondary">Claim Total Paid</td>
+                                                <td>${{friendly_money($note->claim_total_paid)}}</td>
+                                            </tr>
+                                            <tr>
+                                                <td class="text-secondary">Claiming Closed At</td>
+                                                <td>{{$note->claim_closed_at ? friendlier_date_time($note->claim_closed_at) : '-'}}</td>
+                                            </tr>
+                                            </tbody>
+                                        </table>
+                                        <table class="w-25 flex-grow-1 table-bordered table-condensed table-sm table-striped ml-2">
+                                            <tbody>
+                                            <tr>
+                                                <td class="text-secondary">HCP Bill Total Exp.</td>
+                                                <td>${{friendly_money($note->hcp_bill_total_expected)}}</td>
+                                            </tr>
+                                            <tr>
+                                                <td class="text-secondary">NA Bill Total Exp.</td>
+                                                <td>${{friendly_money($note->na_bill_total_expected)}}</td>
+                                            </tr>
+                                            <tr>
+                                                <td class="text-secondary">RMM Bill Total Exp.</td>
+                                                <td>${{friendly_money($note->rmm_bill_total_expected)}}</td>
+                                            </tr>
+                                            <tr>
+                                                <td class="text-secondary">RME Bill Total Exp.</td>
+                                                <td>${{friendly_money($note->rme_bill_total_expected)}}</td>
+                                            </tr>
+                                            <tr>
+                                                <td class="text-secondary">RMS Bill Total Exp.</td>
+                                                <td>${{friendly_money($note->rms_bill_total_expected)}}</td>
+                                            </tr>
+                                            <tr>
+                                                <td class="text-secondary">RMG Bill Total Exp.</td>
+                                                <td>${{friendly_money($note->rmg_bill_total_expected)}}</td>
+                                            </tr>
+                                            <tr>
+                                                <td class="text-secondary">CM Bill Total Exp.</td>
+                                                <td>${{friendly_money($note->cm_bill_total_expected)}}</td>
+                                            </tr>
+                                            </tbody>
+                                        </table>
+                                        <table class="w-25 flex-grow-1 table-bordered table-condensed table-sm table-striped ml-2">
+                                            <tbody>
+                                            <tr>
+                                                <td class="text-secondary">HCP Bill Total Paid</td>
+                                                <td>${{friendly_money($note->hcp_bill_total_paid)}}</td>
+                                            </tr>
+                                            <tr>
+                                                <td class="text-secondary">NA Bill Total Paid</td>
+                                                <td>${{friendly_money($note->na_bill_total_paid)}}</td>
+                                            </tr>
+                                            <tr>
+                                                <td class="text-secondary">RMM Bill Total Paid</td>
+                                                <td>${{friendly_money($note->rmm_bill_total_paid)}}</td>
+                                            </tr>
+                                            <tr>
+                                                <td class="text-secondary">RME Bill Total Paid</td>
+                                                <td>${{friendly_money($note->rme_bill_total_paid)}}</td>
+                                            </tr>
+                                            <tr>
+                                                <td class="text-secondary">RMS Bill Total Paid</td>
+                                                <td>${{friendly_money($note->rms_bill_total_paid)}}</td>
+                                            </tr>
+                                            <tr>
+                                                <td class="text-secondary">RMG Bill Total Paid</td>
+                                                <td>${{friendly_money($note->rmg_bill_total_paid)}}</td>
+                                            </tr>
+                                            <tr>
+                                                <td class="text-secondary">CM Bill Total Paid</td>
+                                                <td>${{friendly_money($note->cm_bill_total_paid)}}</td>
+                                            </tr>
+                                            <!--                                <tr>
+                                    <td class="text-secondary">HCP Company Pro</td>
+                                    <td>{{$note->hcp_company_pro_id}}</td>
+                                </tr>-->
+                                            </tbody>
+                                        </table>
+                                    </div>
+                                </div>
+                            </div>
+                        @endif
+
+                        @if($note->method === 'IN_CLINIC' || $pro->pro_type === 'ADMIN')
+                            <div class="p-3 border-bottom screen-only">
+                                <div class="ml-auto d-inline-flex align-items-center">
+
+                                    <span class="text-secondary font-weight-bold">Pro:&nbsp;</span>
+                                    <b>{{$note->hcpPro ? $note->hcpPro->displayName() : '-'}}</b>
+
+                                    <span class="mx-2 text-secondary">|</span>
+                                    <span>
+                            <span class="text-secondary font-weight-bold">Payer 1°: </span>
+                            <b>
+                                {{$note->hcpCompanyProPayer && $note->hcpCompanyProPayer->company ? $note->hcpCompanyProPayer->company->name : '-'}}
+                                /
+                                {{$note->hcpCompanyProPayer && $note->hcpCompanyProPayer->payer ? $note->hcpCompanyProPayer->payer->name : '-'}}
+                            </b>
+                            <span moe class="ml-1">
+                                <a class="text-primary" href="" show start><i class="fa fa-edit"></i></a>
+                                <form url="/api/note/putHcpCompanyProPayer">
+                                    <input type="hidden" name="uid" value="{{$note->uid}}">
+                                    <div class="mb-2">
+                                        <select name="hcpCompanyProPayerUid" class="form-control form-control-sm">
+                                            <option value="">-- select --</option>
+                                            @foreach($note->hcpPro->companyProPayers as $companyProPayer)
+                                                <option value="{{$companyProPayer->uid}}">{{$companyProPayer->company->name}} / {{$companyProPayer->payer->name}}</option>
+                                            @endforeach
+                                        </select>
+                                    </div>
+                                    <div class="mb-0">
+                                        <button class="btn btn-success btn-sm" submit>Submit</button>
+                                        <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                                    </div>
+                                </form>
+                            </span>
+                            @if($note->hcpCompanyProPayer && $note->hcpCompanyProPayer->payer)
+                                            <span moe class="ml-1">
+                                <a class="text-danger" href="" show start><i class="fa fa-trash-alt"></i></a>
+                                <form url="/api/note/wipeHcpCompanyProPayer">
+                                    <input type="hidden" name="uid" value="{{$note->uid}}">
+                                    <p>Wipe payer from this note?</p>
+                                    <div class="mb-0">
+                                        <button class="btn btn-primary btn-sm" submit>Submit</button>
+                                        <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                                    </div>
+                                </form>
+                            </span>
+                                        @endif
+                        </span>
+
+                                    <span class="mx-2 text-secondary">|</span>
+                                    <span>
+                            <span class="text-secondary font-weight-bold">Payer 2°: </span>
+                        </span>
+
+                                    <span class="mx-2 text-secondary">|</span>
+                                    <span>
+                            <span class="text-secondary font-weight-bold">Location: </span><b>{{$note->hcpCompanyLocation ? $note->hcpCompanyLocation->line1 . ', ' . $note->hcpCompanyLocation->city : '-'}}</b>
+                            <span moe class="ml-1">
+                                <a class="text-primary" href="" show start><i class="fa fa-edit"></i></a>
+                                <form url="/api/note/putHcpCompanyLocation">
+                                    <input type="hidden" name="uid" value="{{$note->uid}}">
+                                    <div class="mb-2">
+                                        <select name="hcpCompanyLocationUid" class="form-control form-control-sm">
+                                            <option value="">-- select --</option>
+                                            @if($note->hcpCompany && $note->hcpCompany->locations)
+                                                @foreach($note->hcpCompany->locations as $location)
+                                                    <option value="{{$location->uid}}">{{$location->line1 . ', ' . $location->city}}</option>
+                                                @endforeach
+                                            @endif
+                                        </select>
+                                    </div>
+                                    <div class="mb-0">
+                                        <button class="btn btn-success btn-sm" submit>Submit</button>
+                                        <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                                    </div>
+                                </form>
+                            </span>
+                            @if($note->hcpCompanyLocation)
+                                            <span moe class="ml-1">
+                                <a class="text-danger" href="" show start><i class="fa fa-trash-alt"></i></a>
+                                <form url="/api/note/wipeHcpCompanyLocation">
+                                    <input type="hidden" name="uid" value="{{$note->uid}}">
+                                    <p>Wipe location from this note?</p>
+                                    <div class="mb-0">
+                                        <button class="btn btn-primary btn-sm" submit>Submit</button>
+                                        <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                                    </div>
+                                </form>
+                            </span>
+                                        @endif
+                        </span>
+                                </div>
+                            </div>
+                        @endif
+
+                        {{-- bills --}}
+                        @if($pro->pro_type === 'ADMIN' || ($note->hcpPro && $pro->id === $note->hcpPro->id) || ($note->allyPro && $pro->id === $note->allyPro->id))
+                            @if($note->bills->count())
+                                <div class="p-3 border-bottom">
+                                    <div class="d-flex align-items-center mb-2">
+                                        <p class="font-weight-bold text-secondary font-size-13 m-0">Bills</p>
+                                        @if($pro->pro_type === 'ADMIN' || ($note->hcpPro && $pro->id === $note->hcpPro->id))
+                                            @include('app/patient/note/_create-bill')
+                                        @endif
+                                    </div>
+
+                                    @if($pro->pro_type === 'ADMIN')
+                                        <table class="table table-sm tabe-striped mb-0 table-bordered">
+                                            <thead class="bg-light">
+                                            <tr class="text-secondary">
+                                                <?php /* <th class="border-bottom-0"></th> */ ?>
+                                                <th class="border-bottom-0">Date</th>
+                                                <th class="border-bottom-0">Service</th>
+                                                <th class="border-bottom-0">Billable</th>
+                                                <th class="border-bottom-0">HCP</th>
+                                                <th class="border-bottom-0 screen-only">Total</th>
+                                                <th class="border-bottom-0">Sign</th>
+                                                <th class="border-bottom-0 screen-only">Bal Post Date</th>
+                                                <th class="border-bottom-0">Verification</th>
+                                                <th class="border-bottom-0">Cancellation</th>
+                                                <th class="border-bottom-0 screen-only">Payment</th>
+                                            </tr>
+                                            </thead>
+                                            <tbody>
+                                            @foreach ($note->bills as $bill)
+                                                <tr class="{{$bill->is_cancelled ? 'bg-light text-secondary' : ''}}">
+                                                    <?php /* <td class="p-0">
+                                        <table class="table-striped table-sm table-condensed border border-left-0 border-top-0 border-bottom-0">
+                                            <tbody>
+                                                <tr><td>collected_amount</td><td>{{$bill->collected_amount}}</td></tr>
+                                                <tr><td>effective_date</td><td>{{$bill->effective_date}}</td></tr>
+                                                <tr><td>has_hcp_been_paid</td><td>{{$bill->has_hcp_been_paid}}</td></tr>
+                                                <tr><td>hcp_expected_payment_amount</td><td>{{$bill->hcp_expected_payment_amount}}</td></tr>
+                                                <tr><td>hcp_payment_amount</td><td>{{$bill->hcp_payment_amount}}</td></tr>
+                                                <tr><td>is_cancelled</td><td>{{$bill->is_cancelled}}</td></tr>
+                                                <tr><td>hcp_payment_pro_transaction_id</td><td>{{$bill->hcp_payment_pro_transaction_id}}</td></tr>
+                                                <tr><td>balance_post_date</td><td>{{$bill->balance_post_date}}</td></tr>
+                                                <tr><td>is_verified</td><td>{{$bill->is_verified}}</td></tr>
+                                                <tr><td>is_cancellation_acknowledged</td><td>{{$bill->is_cancellation_acknowledged}}</td></tr>
+                                                <tr><td>is_cancelled_by_administrator</td><td>{{$bill->is_cancelled_by_administrator}}</td></tr>
+                                                <tr><td>total_expected</td><td>{{$bill->total_expected}}</td></tr>
+                                                <tr><td>total_paid</td><td>{{$bill->total_paid}}</td></tr>
+                                            </tbody>
+                                        </table>
+                                    </td> */ ?>
+                                                    <td class="text-nowrap">{{friendlier_date_time($bill->effective_date, false)}}</td>
+                                                    <td>{{$bill->code}}</td>
+                                                    <td class="">
+                                                        @if(strpos(strtolower($bill->code), 'treatment services') !== FALSE)
+                                                            <?php
+                                                            $totalSeconds = $bill->number_of_units * 3600;
+                                                            $remainder = $totalSeconds % 60;
+                                                            if ($remainder !== 0) {
+                                                                if ($remainder < 30) {
+                                                                    $totalSeconds = $totalSeconds - $remainder;
+                                                                }
+                                                                else {
+                                                                    $totalSeconds = $totalSeconds + (60 - $remainder);
+                                                                }
+                                                            }
+                                                            ?>
+                                                            {{ time_in_hrminsec($totalSeconds) }}
+                                                        @else
+                                                            @if(!!$bill->number_of_units)
+                                                                {{ $bill->number_of_units }} unit(s)
+                                                            @else
+                                                                -
+                                                            @endif
+                                                        @endif
+                                                    </td>
+                                                    <td class="">
+                                                        <div class="text-nowrap font-weight-bold text-secondary">{{ $bill->hcp->displayName() }} (HCP)</div>
+                                                        <div class="text-nowrap mt-1 screen-only">
+                                                            <span class="text-secondary">Paid: </span>
+                                                            <span>{{ $bill->has_hcp_been_paid ? 'Yes' : 'No' }}</span>
+                                                        </div>
+                                                        @if(!$bill->has_hcp_been_paid)
+                                                            <div class="text-nowrap mt-1 screen-only">
+                                                                <span class="text-secondary">Expected: </span>
+                                                                <span class="font-weight-bold">${{ $bill->hcp_expected_payment_amount }}</span>
+                                                            </div>
+                                                        @else
+                                                            <div class="text-nowrap mt-1 screen-only">
+                                                                <span class="text-secondary">Amount: </span>
+                                                                <span class="font-weight-bold">${{ $bill->hcp_payment_amount }}</span>
+                                                            </div>
+                                                        @endif
+                                                        @if($bill->ally)
+                                                            <hr>
+                                                            <div class="text-nowrap font-weight-bold text-secondary">{{ $bill->ally->displayName() }} (NA)</div>
+                                                            <div class="text-nowrap mt-1 screen-only">
+                                                                <span class="text-secondary">Paid: </span>
+                                                                <span>{{ $bill->has_na_been_paid ? 'Yes' : 'No' }}</span>
+                                                            </div>
+                                                            @if(!$bill->has_na_been_paid)
+                                                                <div class="text-nowrap mt-1 screen-only">
+                                                                    <span class="text-secondary">Expected: </span>
+                                                                    <span class="font-weight-bold">${{ $bill->na_expected_payment_amount }}</span>
+                                                                </div>
+                                                            @else
+                                                                <div class="text-nowrap mt-1 screen-only">
+                                                                    <span class="text-secondary">Amount: </span>
+                                                                    <span class="font-weight-bold">${{ $bill->na_payment_amount }}</span>
+                                                                </div>
+                                                            @endif
+                                                        @endif
+
+                                                    </td>
+                                                    <td class="pr-3 screen-only">
+                                                        @if($bill->has_hcp_been_paid)
+                                                            <span class="text-secondary">Paid. </span>
+                                                            <span class="font-weight-bold">${{ friendly_money($bill->total_paid) }}</span>
+                                                        @else
+                                                            <span class="text-secondary">Exp. </span>
+                                                            <span class="font-weight-bold">{{ $bill->total_expected ? '$' . friendly_money($bill->total_expected) : '-' }}</span>
+                                                        @endif
+                                                    </td>
+                                                    <td>
+                                                        @if(!$bill->is_cancelled)
+                                                            @if($bill->is_signed_by_hcp)
+                                                                <span class="d-block text-secondary text-nowrap">
+                                                        <i class="fa fa-check"></i>
+                                                        HCP Signed
+                                                    </span>
+                                                            @else
+                                                                <span moe
+                                                                      class="d-block {{ $bill->hcp_pro_id !== $pro->id ? 'moe-disabled' : '' }}"
+                                                                      title="{{ $bill->hcp_pro_id !== $pro->id ? 'Only the bill\'s HCP can sign' : '' }}">
+                                                    <a class="" href="" show start>Sign As HCP</a>
+                                                    <form url="/api/bill/signAsHcp">
+                                                        <input type="hidden" name="uid" value="{{$bill->uid}}">
+                                                        <p>Sign this bill as HCP?</p>
+                                                        <div class="mb-0">
+                                                            <button class="btn btn-success btn-sm" submit>Sign</button>
+                                                            <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                                                        </div>
+                                                    </form>
+                                                </span>
+                                                            @endif
+
+                                                            @if($bill->is_signed_by_na)
+                                                                <span class="d-block text-secondary text-nowrap">
+                                                    <i class="fa fa-check"></i>
+                                                    NA Signed
+                                                </span>
+                                                            @else
+                                                                <span moe
+                                                                      class="d-block {{ $bill->na_pro_id !== $pro->id ? 'moe-disabled' : '' }}"
+                                                                      title="{{ $bill->na_pro_id !== $pro->id ? 'Only the bill\'s NA can sign' : '' }}">
+                                                    <a class="" href="" show start>Sign As NA</a>
+                                                    <form url="/api/bill/signAsNa">
+                                                        <input type="hidden" name="uid" value="{{$bill->uid}}">
+                                                        <p>Sign this bill as NA?</p>
+                                                        <div class="mb-0">
+                                                            <button class="btn btn-success btn-sm" submit>Sign</button>
+                                                            <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                                                        </div>
+                                                    </form>
+                                                </span>
+                                                            @endif
+                                                        @endif
+                                                    </td>
+                                                    <td class="screen-only">
+                                                        @if(!$bill->is_cancelled)
+                                                            <span class="d-block" moe>
+                                                <a class="" href="" show start>
+                                                    {{$bill->balance_post_date ? friendlier_date_time($bill->balance_post_date, false) : '(not set)' }}
+                                                </a>
+                                                <form url="/api/bill/updateBalancePostDate">
+                                                    <input type="hidden" name="uid" value="{{$bill->uid}}">
+                                                    <p>Update Balance Post Date</p>
+                                                    <div class="mb-0">
+                                                        <input type="date" class="text form-control form-control-sm" name="balancePostDate" value="{{$bill->balance_post_date}}" placeholder="balance post date"><br>
+                                                        <button class="btn btn-success btn-sm" submit>Submit</button>
+                                                        <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                                                    </div>
+                                                </form>
+                                            </span>
+                                                        @endif
+                                                    </td>
+                                                    <td> <!-- verification -->
+                                                        @if($pro->pro_type === 'ADMIN' && !$bill->is_cancelled)
+                                                            @if(!$bill->is_verified)
+                                                                <div class="text-warning-mellow font-weight-bold">Not Verified</div>
+                                                                <span class="d-block mt-1" moe>
+                                                    <a href="" show start>Mark Verified</a>
+                                                    <form url="/api/bill/markAsVerified">
+                                                        <input type="hidden" name="uid" value="{{$bill->uid}}">
+                                                        <p>Mark As Verfified?</p>
+                                                        <div class="mb-0">
+                                                            <button class="btn btn-success btn-sm" submit>Submit</button>
+                                                            <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                                                        </div>
+                                                    </form>
+                                                </span>
+                                                            @else
+                                                                <div class="text-success font-weight-bold"><i class="fa fa-check"></i> Verified</div>
+                                                                <span class="d-block mt-1" moe>
+                                                    <a class="" href="" show start>Undo</a>
+                                                    <form url="/api/bill/undoMarkAsVerified">
+                                                        <input type="hidden" name="uid" value="{{$bill->uid}}">
+                                                        <p>Undo Mark As Verfified?</p>
+                                                        <div class="mb-0">
+                                                            <button class="btn btn-success btn-sm" submit>Submit</button>
+                                                            <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                                                        </div>
+                                                    </form>
+                                                </span>
+                                                            @endif
+                                                        @endif
+                                                    </td>
+                                                    <td>  <!-- cancellation -->
+                                                        @if($bill->is_cancelled)
+                                                            <div class="text-warning-mellow font-weight-bold">Cancelled</div>
+                                                            @if($bill->cancellation_memo)
+                                                                <div class="text-dark text-sm font-italic my-1">{{$bill->cancellation_memo}}</div>
+                                                            @endif
+                                                            @if($bill->is_cancelled_by_administrator)
+                                                                <div class="text-secondary text-sm">(by Administrator)</div>
+                                                            @endif
+                                                            <div moe class="mt-1">
+                                                                <a class="" href="" show start>Update Memo</a>
+                                                                <form url="/api/bill/updateCancellationMemo">
+                                                                    <input type="hidden" name="uid" value="{{$bill->uid}}">
+                                                                    <p>Update Cancellation Memo</p>
+                                                                    <div class="mb-2">
+                                                                        <textarea class="text form-control form-control-sm" name="cancellationMemo" placeholder="">{{$bill->cancellation_memo ? $bill->cancellation_memo : 'Insufficient documentation for billable service.'}}</textarea>
+                                                                    </div>
+                                                                    <div>
+                                                                        <button class="btn btn-success btn-sm" submit>Submit</button>
+                                                                        <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                                                                    </div>
+                                                                </form>
+                                                            </div>
+                                                        @else
+                                                            <span class="d-block" moe relative="">
+                                                <a class="text-danger" href="" show start>Cancel</a>
+                                                <form url="/api/bill/markCancelled" right="">
+                                                    <input type="hidden" name="uid" value="{{$bill->uid}}">
+                                                    <p class="mb-2">Cancel this bill?</p>
+                                                    <div class="mb-2">
+                                                        <label class="mb-1 text-secondary">Cancellation Memo</label>
+                                                        <textarea type="text" name="memo" placeholder="Memo" class="form-control form-control-sm">Insufficient documentation for billable service.</textarea>
+                                                    </div>
+                                                    <div class="mb-0">
+                                                        <button class="btn btn-danger btn-sm" submit>Yes</button>
+                                                        <button class="btn btn-default border btn-sm" cancel>No</button>
+                                                    </div>
+                                                </form>
+                                            </span>
+                                                        @endif
+
+                                                        @if($bill->is_cancelled && !$bill->is_cancellation_acknowledged)
+                                                            <div class="mt-2 text-secondary">
+                                                                <i class="fa fa-exclamation-triangle"></i>
+                                                                Not Acknowledged
+                                                            </div>
+                                                            <div class="d-block mt-1" moe>
+                                                                <a class="" href="" show start>Ack. Cancellation</a>
+                                                                <form url="/api/bill/acknowledgeCancellation">
+                                                                    <input type="hidden" name="uid" value="{{$bill->uid}}">
+                                                                    <p>Acknowledge Cancellation?</p>
+                                                                    <div class="mb-0">
+                                                                        {{--<input type="text" class="text form-control form-control-sm" name="cancellationMemo" value="{{$bill->cancellation_memo}}" placeholder=""><br>--}}
+                                                                        <button class="btn btn-primary btn-sm" submit>Submit</button>
+                                                                        <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                                                                    </div>
+                                                                </form>
+                                                            </div>
+                                                        @endif
+
+                                                        @if($bill->is_cancellation_acknowledged && !$note->is_billing_marked_done)
+                                                            <div class="mt-2 text-secondary">
+                                                                <i class="fa fa-check"></i>
+                                                                Acknowledged
+                                                            </div>
+                                                            <div class="d-block mt-1" moe>
+                                                                <a class="" href="" show start>Undo Cancellation Ack.</a>
+                                                                <form url="/api/bill/undoAcknowledgeCancellation">
+                                                                    <input type="hidden" name="uid" value="{{$bill->uid}}">
+                                                                    <p>Undo Acknowledge Cancellation?</p>
+                                                                    <div class="mb-0">
+                                                                        <button class="btn btn-success btn-sm" submit>Submit</button>
+                                                                        <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                                                                    </div>
+                                                                </form>
+                                                            </div>
+                                                        @endif
+
+                                                    </td>
+                                                    <td class="screen-only"> <!-- submit payment -->
+                                                        <div class="my-1">
+                                                            @if(!$bill->is_cancelled && !$bill->has_hcp_been_paid )
+                                                                @if(+$bill->hcp_expected_payment_amount && $bill->is_signed_by_hcp)
+                                                                    <span class="d-block" moe relative="">
+                                                        <a class="font-weight-bold" href="" show start>Submit Payment For HCP</a>
+                                                        <form url="/api/bill/payHcpAmount" right>
+                                                            <input type="hidden" name="uid" value="{{$bill->uid}}">
+                                                            <p>Submit Payment</p>
+                                                            <div class="mb-0">
+                                                                <input type="text" class="text form-control form-control-sm" name="hcpPaymentAmount" value="{{$bill->hcp_expected_payment_amount}}" placeholder="amount"><br>
+                                                                <button class="btn btn-success btn-sm" submit>Submit</button>
+                                                                <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                                                            </div>
+                                                        </form>
+                                                    </span>
+                                                                @else
+                                                                    @if(!+$bill->hcp_expected_payment_amount)
+                                                                        <div class="mb-1 text-danger">
+                                                                            <i class="fa fa-exclamation-triangle"></i>
+                                                                            HCP expected amount is invalid
+                                                                        </div>
+                                                                    @endif
+                                                                    @if(!$bill->is_signed_by_hcp)
+                                                                        <div class="mb-1 text-danger">
+                                                                            <i class="fa fa-exclamation-triangle"></i>
+                                                                            HCP has not signed the bill
+                                                                        </div>
+                                                                    @endif
+                                                                @endif
+                                                            @endif
+                                                        </div>
+                                                        <div class="my-1">
+                                                            @if(!$bill->is_cancelled && !$bill->has_na_been_paid && $bill->ally)
+                                                                @if(+$bill->na_expected_payment_amount && $bill->is_signed_by_na)
+                                                                    <span class="d-block" moe relative="">
+                                                        <a class="font-weight-bold" href="" show start>Submit Payment For NA</a>
+                                                        <form url="/api/bill/payNaAmount" right>
+                                                            <input type="hidden" name="uid" value="{{$bill->uid}}">
+                                                            <p>Submit Payment For NA</p>
+                                                            <div class="mb-0">
+                                                                <input type="text" class="text form-control form-control-sm" name="naPaymentAmount" value="{{$bill->na_expected_payment_amount}}" placeholder="amount"><br>
+                                                                <button class="btn btn-success btn-sm" submit>Submit</button>
+                                                                <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                                                            </div>
+                                                        </form>
+                                                    </span>
+                                                                @else
+                                                                    @if(!+$bill->na_expected_payment_amount)
+                                                                        <div class="mb-1 text-danger">
+                                                                            <i class="fa fa-exclamation-triangle"></i>
+                                                                            NA expected amount is invalid
+                                                                        </div>
+                                                                    @endif
+                                                                    @if(!$bill->is_signed_by_na)
+                                                                        <div class="mb-1 text-danger">
+                                                                            <i class="fa fa-exclamation-triangle"></i>
+                                                                            NA has not signed the bill
+                                                                        </div>
+                                                                    @endif
+                                                                @endif
+                                                            @endif
+                                                        </div>
+                                                    </td>
+                                                </tr>
+                                            @endforeach
+                                            </tbody>
+                                        </table>
+                                    @else
+                                        <table class="table table-sm tabe-striped mb-3 border-left border-right border-bottom">
+                                            <thead class="bg-light">
+                                            <tr>
+                                                <th class="border-bottom-0 pl-3">HCP</th>
+                                                @if($note->ally_pro_id === $pro->id)
+                                                    <th class="border-bottom-0 pl-3">NA</th>
+                                                @endif
+                                                <th class="border-bottom-0 w-25 pl-3">Service</th>
+                                                {{--<th class="border-bottom-0 w-25 pl-2">Reason</th>--}}
+                                                <th class="border-bottom-0 pl-3">Billable</th>
+                                                <th class="border-bottom-0 pl-2">Amount</th>
+                                                <th class="border-bottom-0"></th>
+                                            </tr>
+                                            </thead>
+                                            <tbody>
+                                            @foreach ($note->bills as $bill)
+                                                <tr>
+                                                    <td class="pl-3">{{ $bill->hcp->displayName() }}</td>
+                                                    @if($note->ally_pro_id === $pro->id)
+                                                        <td class="pl-3">{{ $note->allyPro->displayName() }}</td>
+                                                    @endif
+                                                    <td class="pl-3 {{ $bill->is_cancelled ? 'text-secondary' : '' }}">{{$bill->code}}</td>
+                                                    {{--<td class="pl-2">
+                                                        {{ $bill->reason1 }}
+                                                        <div class="text-secondary small">{{ $bill->reason2 }}</div>
+                                                    </td>--}}
+                                                    <td class="pl-3">
+                                                        @if(strpos(strtolower($bill->code), 'treatment services') !== FALSE)
+                                                            <?php
+                                                            $totalSeconds = $bill->number_of_units * 3600;
+                                                            $remainder = $totalSeconds % 60;
+                                                            if ($remainder !== 0) {
+                                                                if ($remainder < 30) {
+                                                                    $totalSeconds = $totalSeconds - $remainder;
+                                                                }
+                                                                else {
+                                                                    $totalSeconds = $totalSeconds + (60 - $remainder);
+                                                                }
+                                                            }
+                                                            ?>
+                                                            {{ time_in_hrminsec($totalSeconds) }}
+                                                        @else
+                                                            @if(!!$bill->number_of_units)
+                                                                {{ $bill->number_of_units }} unit(s)
+                                                            @else
+                                                                -
+                                                            @endif
+                                                        @endif
+                                                    </td>
+                                                    <td class="pl-2">
+                                                        @if($bill->hcp_pro_id === $pro->id)
+                                                            @if($bill->has_hcp_been_paid)
+                                                                <span class="text-dark">Processed:</span><span class="font-weight-bold text-success ml-2">${{ $bill->hcp_payment_amount }}</span>
+                                                            @else
+                                                                <span class="text-dark">Expected:</span><span class="font-weight-bold text-dark ml-2">{{ $bill->hcp_expected_payment_amount ? '$' . $bill->hcp_expected_payment_amount : '-' }}</span>
+                                                            @endif
+                                                        @elseif($bill->na_pro_id === $pro->id)
+                                                            @if($bill->has_na_been_paid)
+                                                                <span class="text-dark">Processed:</span><span class="font-weight-bold text-success ml-2">${{ $bill->na_payment_amount }}</span>
+                                                            @else
+                                                                <span class="text-dark">Expected:</span><span class="font-weight-bold text-dark ml-2">{{ $bill->na_expected_payment_amount ? '$' . $bill->na_expected_payment_amount : '-' }}</span>
+                                                            @endif
+                                                        @endif
+                                                    </td>
+                                                    <td>
+                                                        <div class="d-flex align-items-center">
+                                                            @if(!$bill->is_cancelled)
+                                                                @if($bill->is_signed_by_hcp)
+                                                                    <span class="d-block text-secondary">
+                                                        <i class="fa fa-check"></i>
+                                                        HCP Signed
+                                                    </span>
+                                                                @else
+                                                                    <span moe
+                                                                          class="d-block {{ $bill->hcp_pro_id !== $pro->id ? 'moe-disabled' : '' }}"
+                                                                          title="{{ $bill->hcp_pro_id !== $pro->id ? 'Only the bill\'s HCP can sign' : '' }}">
+                                                        <a class="" href="" show start>Sign as HCP</a>
+                                                        <form url="/api/bill/signAsHcp">
+                                                            <input type="hidden" name="uid" value="{{$bill->uid}}">
+                                                            <p>Sign this bill as HCP?</p>
+                                                            <div class="mb-0">
+                                                                <button class="btn btn-success btn-sm" submit>Sign</button>
+                                                                <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                                                            </div>
+                                                        </form>
+                                                    </span>
+                                                                @endif
+                                                                @if($bill->na_pro_id === $pro->id)
+                                                                    <span class="mx-2 text-secondary">|</span>
+                                                                    @if($bill->is_signed_by_na)
+                                                                        <span class="d-block text-secondary">
+                                                            <i class="fa fa-check"></i>
+                                                            NA Signed
+                                                        </span>
+                                                                    @else
+                                                                        <span moe
+                                                                              class="d-block {{ $bill->na_pro_id !== $pro->id ? 'moe-disabled' : '' }}"
+                                                                              title="{{ $bill->hcp_pro_id !== $pro->id ? 'Only the bill\'s NA can sign' : '' }}">
+                                                            <a class="" href="" show start>Sign as NA</a>
+                                                            <form url="/api/bill/signAsNa">
+                                                                <input type="hidden" name="uid" value="{{$bill->uid}}">
+                                                                <p>Sign this bill as NA?</p>
+                                                                <div class="mb-0">
+                                                                    <button class="btn btn-success btn-sm" submit>Sign</button>
+                                                                    <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                                                                </div>
+                                                            </form>
+                                                        </span>
+                                                                    @endif
+                                                                @endif
+                                                            @endif
+                                                            @if(!$bill->has_hcp_been_paid && $pro->pro_type === 'ADMIN')
+                                                                <span class="mx-2 text-secondary">|</span>
+                                                                <span class="d-block" moe>
+                                                    <a class="text-danger" href="" show start>Submit Payment</a>
+                                                    <form url="/api/bill/payHcpAmount">
+                                                        <input type="hidden" name="uid" value="{{$bill->uid}}">
+                                                        <p>Submit payment:</p>
+                                                        <div class="mb-0">
+                                                            <input type="text" class="text form-control form-control-sm" name="hcpPaymentAmount" value="{{$bill->hcp_expected_payment_amount}}" placeholder="amount"><br>
+                                                            <button class="btn btn-success btn-sm" submit>Submit</button>
+                                                            <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                                                        </div>
+                                                    </form>
+                                                </span>
+                                                            @endif
+                                                            @if(!$bill->has_na_been_paid && $bill->ally && $pro->pro_type === 'ADMIN')
+                                                                <span class="d-block" moe relative="">
+                                                    <a class="font-weight-bold" href="" show start>Submit Payment For NA</a>
+                                                    <form url="/api/bill/payNaAmount" right>
+                                                        <input type="hidden" name="uid" value="{{$bill->uid}}">
+                                                        <p>Submit Payment For NA</p>
+                                                        <div class="mb-0">
+                                                            <input type="text" class="text form-control form-control-sm" name="naPaymentAmount" value="{{$bill->na_expected_payment_amount}}" placeholder="amount"><br>
+                                                            <button class="btn btn-success btn-sm" submit>Submit</button>
+                                                            <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                                                        </div>
+                                                    </form>
+                                                </span>
+                                                            @endif
+                                                            @if($bill->is_cancelled)
+                                                                <span class="mx-2 text-secondary">|</span>
+                                                                <span class="d-block text-secondary">
+                                                    Cancelled
+                                                </span>
+                                                            @else
+                                                                <span class="mx-2 text-secondary">|</span>
+                                                                <span class="d-block" moe>
+                                                    <a class="text-danger" href="" show start>Cancel</a>
+                                                    <form url="/api/bill/markCancelled" right>
+                                                        <input type="hidden" name="uid" value="{{$bill->uid}}">
+                                                        <p>Cancel this bill?</p>
+                                                        <div class="mb-0">
+                                                            <button class="btn btn-danger btn-sm" submit>Yes</button>
+                                                            <button class="btn btn-default border btn-sm" cancel>No</button>
+                                                        </div>
+                                                    </form>
+                                                </span>
+                                                            @endif
+                                                        </div>
+                                                    </td>
+                                                </tr>
+                                            @endforeach
+                                            </tbody>
+                                        </table>
+                                    @endif
+
+                                </div>
+                            @else
+                                <div class="p-3 d-flex  border-bottom">
+                                    <p class="font-weight-bold mb-0 text-secondary">No bills in this note</p>
+                                    @include('app/patient/note/_create-bill')
+                                </div>
+                            @endif
+                        @endif
+
+                        {{-- claims --}}
+                        @if($pro->pro_type === 'ADMIN')
+                            @if($note->claims->count())
+                                <div class="screen-only p-3">
+                                    <div class="d-flex align-items-center mb-2">
+                                        <p class="font-weight-bold text-secondary m-0">Claims</p>
+                                        @include('app/patient/note/_create-claim')
+                                        <div class="ml-auto">
+                                            <select class="form-control form-control-sm"
+                                                    onchange="fastLoad('{{route('patients.view.notes.view.dashboard', ['patient' => $patient, 'note' => $note])}}?claims-filter=' + this.value)">
+                                                <option value="active" {{!request('claims-filter') || request('claims-filter') === 'active' ? 'selected' : ''}}>Active Claims</option>
+                                                <option value="all" {{request('claims-filter') === 'all' ? 'selected' : ''}}>All Claims</option>
+                                            </select>
+                                        </div>
+                                    </div>
+
+                                    <table class="table table-sm tabe-striped mb-3 border-left border-right border-bottom">
+                                        <thead class="bg-light">
+                                        <tr>
+                                            <th class="border-bottom-0 pl-2">IID</th>
+                                            <th class="border-bottom-0">Details</th>
+                                            <th class="border-bottom-0">Status</th>
+                                            <th class="border-bottom-0">Submissions</th>
+                                        </tr>
+                                        </thead>
+                                        <tbody>
+                                        @foreach ($note->claims as $claim)
+                                            @if($claim->status !== 'CANCELLED' || request('claims-filter') === 'all')
+                                                <tr class="bg-secondary on-hover-opaque">
+                                                    <td colspan="5" class="pt-0 pb-1"></td>
+                                                </tr>
+                                                <tr class="{{ $claim->status === 'CANCELLED' ? 'text-secondary bg-light on-hover-opaque' : '' }}">
+                                                    <td class="pl-2">
+                                                        <div>{{ $claim->iid }}</div>
+                                                        <div class="text-sm text-secondary font-weight-bold mt-1">Current Version:</div>
+                                                        <div class="text-sm text-secondary">{{$claim->currentVersion ? friendlier_date_time($claim->currentVersion->created_at) : '-'}}</div>
+                                                        @if($claim->status === 'CANCELLED')
+                                                            <div class="text-secondary font-weight-bold text-sm mt-1">[CANCELLED]</div>
+                                                        @else
+                                                            <div moe class="text-left mt-1" title="Cancel Claim">
+                                                                <a class="" href="" show start>Cancel</a>
+                                                                <form url="/api/claim/updateStatus">
+                                                                    <input type="hidden" name="uid" value="{{$claim->uid}}">
+                                                                    <input type="hidden" name="status" value="CANCELLED">
+                                                                    <p>Cancel this claim?</p>
+                                                                    <div class="mb-2">
+                                                                        <label for="" class="control-label">Cancellation Memo</label>
+                                                                        <textarea name="memo" class="form-control"></textarea>
+                                                                    </div>
+                                                                    <div class="mb-0">
+                                                                        <button class="btn btn-primary btn-sm" submit>Submit</button>
+                                                                        <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                                                                    </div>
+                                                                </form>
+                                                            </div>
+                                                        @endif
+                                                    </td>
+                                                    <td class="p-0 border-left border-right">
+                                                        @if($claim->lines->count())
+                                                            <table class="table table-sm table-condensed border-0 mb-0">
+                                                                <thead>
+                                                                <tr class="bg-light">
+                                                                    <th class="border-0">CPT</th>
+                                                                    <th class="border-0">DOS</th>
+                                                                    <th class="border-0">ICDs</th>
+                                                                </tr>
+                                                                </thead>
+                                                                <tbody class="pb-3">
+                                                                @foreach($claim->lines as $line)
+                                                                    <tr class="claim-line">
+                                                                        <td>{{$line->cpt}}
+                                                                            <div>Units: <b>{{!@$line->units ? 1 : $line->units}}</b></div>
+                                                                        </td>
+                                                                        <td class="text-nowrap">{{friendlier_date($line->date_of_service)}}</td>
+                                                                        <td>
+                                                                            @if(count($line->claimLineIcds))
+                                                                                @foreach($line->claimLineIcds as $icd)
+                                                                                    <div>
+                                                                                        <b class="c-pointer border-secondary border-bottom" title="{{$icd->description}}">{{$icd->code}}</b>
+                                                                                    </div>
+                                                                                @endforeach
+                                                                            @else
+                                                                                <p>No ICDs set</p>
+                                                                            @endif
+                                                                        </td>
+                                                                    </tr>
+                                                                @endforeach
+                                                                </tbody>
+                                                            </table>
+                                                        @else
+                                                            <p>No lines for this claim</p>
+                                                        @endif
+                                                    </td>
+                                                    <td class="border-right p-0">
+
+                                                        <!-- payer, company, location -->
+                                                        <div class="p-1">
+                                                            <div class="mt-1">
+                                                                <div>
+                                                                    <span class="text-secondary text-sm">Payer (1°): </span>
+                                                                    <b>{{$claim->primaryPayer ? $claim->primaryPayer->name : '-'}}</b>
+                                                                    @if(0 && $claim->status !== 'CANCELLED')
+                                                                        <span moe class="ml-1">
+                                                            <a class="text-primary" href="" show start><i class="fa fa-edit"></i></a>
+                                                            <form url="/api/claim/putPrimaryPayer">
+                                                                <input type="hidden" name="uid" value="{{$claim->uid}}">
+                                                                <div class="mb-2">
+                                                                    <select name="primaryPayerUid" class="form-control form-control-sm">
+                                                                        <option value="">-- select --</option>
+                                                                        @foreach($note->hcpPro->companyProPayers as $companyProPayer)
+                                                                            <option value="{{$companyProPayer->payer->uid}}"
+                                                                                    {{$claim->primaryPayer && $claim->primaryPayer->uid === $companyProPayer->payer->uid ? 'selected' : ''}}>{{$companyProPayer->payer->name}}</option>
+                                                                        @endforeach
+                                                                    </select>
+                                                                </div>
+                                                                <div class="mb-0">
+                                                                    <button class="btn btn-primary btn-sm" submit>Submit</button>
+                                                                    <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                                                                </div>
+                                                            </form>
+                                                        </span>
+                                                                        @if($claim->primaryPayer)
+                                                                            <span moe class="ml-1">
+                                                            <a class="text-danger" href="" show start><i class="fa fa-trash-alt"></i></a>
+                                                            <form url="/api/claim/wipePrimaryPayer">
+                                                                <input type="hidden" name="uid" value="{{$claim->uid}}">
+                                                                <p>Wipe payer from this claim?</p>
+                                                                <div class="mb-0">
+                                                                    <button class="btn btn-primary btn-sm" submit>Submit</button>
+                                                                    <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                                                                </div>
+                                                            </form>
+                                                        </span>
+                                                                        @endif
+                                                                    @endif
+                                                                </div>
+                                                                <div class="py-1 border-bottom d-flex align-items-center">
+                                                                    <span class="text-secondary text-sm pr-1">Status: </span>
+                                                                    <div>
+                                                                        {{$claim->status ? $claim->status : '(not set)'}}
+                                                                        @if($claim->status !== 'CANCELLED')
+                                                                            <span moe class="d-inline-block text-left ml-1" title="Update Status">
+                                                                    <a class="" href="" show start><i class="fa fa-edit"></i></a>
+                                                                    <form url="/api/claim/updateStatus">
+                                                                        <input type="hidden" name="uid" value="{{$claim->uid}}">
+                                                                        <div class="mb-2">
+                                                                            <label for="" class="control-label">Status</label>
+                                                                            <select name="status" class="form-control form-control-sm" required>
+                                                                                <option value="">-- select --</option>
+                                                                                <option value="NEW" {{$claim->status === 'NEW' ? 'selected' : ''}}>New</option>
+                                                                                <option value="PICKED_UP" {{$claim->status === 'PICKED_UP' ? 'selected' : ''}}>Picked Up</option>
+                                                                                <option value="SUBMITTED" {{$claim->status === 'SUBMITTED' ? 'selected' : ''}}>Submitted</option>
+                                                                                <option value="IN_PROCESS" {{$claim->status === 'IN_PROCESS' ? 'selected' : ''}}>In Process</option>
+                                                                                <option value="ACCEPTED" {{$claim->status === 'ACCEPTED' ? 'selected' : ''}}>Accepted</option>
+                                                                                <option value="REJECTED" {{$claim->status === 'REJECTED' ? 'selected' : ''}}>Rejected</option>
+                                                                                <option value="ABANDONED" {{$claim->status === 'ABANDONED' ? 'selected' : ''}}>Abandoned</option>
+                                                                            </select>
+                                                                        </div>
+                                                                        <div class="mb-2">
+                                                                            <label for="" class="control-label">Status Memo</label>
+                                                                            <textarea name="memo" class="form-control"></textarea>
+                                                                        </div>
+                                                                        <div class="mb-0">
+                                                                            <button class="btn btn-primary btn-sm" submit>Submit</button>
+                                                                            <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                                                                        </div>
+                                                                    </form>
+                                                                </span>
+                                                                        @endif
+                                                                    </div>
+                                                                    @if($claim->status_memo)
+                                                                        <div class="text-secondary font-italic text-sm">{{$claim->status_memo}}</div>
+                                                                    @endif
+                                                                </div>
+                                                            </div>
+
+                                                            <div class="mt-1">
+                                                                <span class="text-secondary text-sm">Payer (2°): </span>
+                                                                <b>-</b>
+                                                            </div>
+
+                                                            <div class="mt-1">
+                                                                <span class="text-secondary text-sm">Company: </span>
+                                                                <b>{{$claim->companyPro && $claim->companyPro->company ? $claim->companyPro->company->name : '-'}}</b>
+                                                                @if(0 && $claim->status !== 'CANCELLED')
+                                                                    <span moe class="ml-1">
+                                                            <a class="text-primary" href="" show start><i class="fa fa-edit"></i></a>
+                                                            <form url="/api/claim/putCompanyPro">
+                                                                <input type="hidden" name="uid" value="{{$claim->uid}}">
+                                                                <div class="mb-2">
+                                                                    <select name="companyProUid" class="form-control form-control-sm">
+                                                                        <option value="">-- select --</option>
+                                                                        @foreach($note->hcpPro->companyProPayers as $companyProPayer)
+                                                                            <option value="{{$companyProPayer->companyPro->uid}}"
+                                                                                    {{$claim->companyPro && $claim->companyPro->uid === $companyProPayer->companyPro->uid ? 'selected' : ''}}>{{$companyProPayer->company->name}}</option>
+                                                                        @endforeach
+                                                                    </select>
+                                                                </div>
+                                                                <div class="mb-0">
+                                                                    <button class="btn btn-primary btn-sm" submit>Submit</button>
+                                                                    <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                                                                </div>
+                                                            </form>
+                                                        </span>
+                                                                    @if($claim->companyPro && $claim->companyPro->company)
+                                                                        <span moe class="ml-1">
+                                                                <a class="text-danger" href="" show start><i class="fa fa-trash-alt"></i></a>
+                                                                <form url="/api/claim/wipeCompanyPro">
+                                                                    <input type="hidden" name="uid" value="{{$claim->uid}}">
+                                                                    <p>Wipe company from this claim?</p>
+                                                                    <div class="mb-0">
+                                                                        <button class="btn btn-primary btn-sm" submit>Submit</button>
+                                                                        <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                                                                    </div>
+                                                                </form>
+                                                            </span>
+                                                                    @endif
+                                                                @endif
+                                                            </div>
+
+                                                            <div class="mt-1">
+                                                                <span class="text-secondary text-sm">Location: </span>
+                                                                <b>{{$claim->companyLocation ? $claim->companyLocation->line1 . ', ' . $claim->companyLocation->city : '-'}}</b>
+                                                                @if(0 && $claim->status !== 'CANCELLED')
+                                                                    <span moe class="ml-1">
+                                                            <a class="text-primary" href="" show start><i class="fa fa-edit"></i></a>
+                                                            <form url="/api/claim/putCompanyLocation">
+                                                                <input type="hidden" name="uid" value="{{$claim->uid}}">
+                                                                <div class="mb-2">
+                                                                    <select name="companyLocationUid" class="form-control form-control-sm">
+                                                                        <option value="">-- select --</option>
+                                                                        @if($claim->company && $claim->company->locations)
+                                                                            @foreach($claim->company->locations as $location)
+                                                                                <option value="{{$location->uid}}"
+                                                                                        {{$claim->companyLocation && $claim->companyLocation->uid === $location->uid ? 'selected' : ''}}>
+                                                                                    {{$location->line1 . ', ' . $location->city}}
+                                                                                </option>
+                                                                            @endforeach
+                                                                        @endif
+                                                                    </select>
+                                                                </div>
+                                                                <div class="mb-0">
+                                                                    <button class="btn btn-success btn-sm" submit>Submit</button>
+                                                                    <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                                                                </div>
+                                                            </form>
+                                                        </span>
+                                                                    @if($claim->companyLocation)
+                                                                        <span moe class="ml-1">
+                                                            <a class="text-danger" href="" show start><i class="fa fa-trash-alt"></i></a>
+                                                            <form url="/api/claim/wipeCompanyLocation">
+                                                                <input type="hidden" name="uid" value="{{$claim->uid}}">
+                                                                <p>Wipe location from this claim?</p>
+                                                                <div class="mb-0">
+                                                                    <button class="btn btn-primary btn-sm" submit>Submit</button>
+                                                                    <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                                                                </div>
+                                                            </form>
+                                                        </span>
+                                                                    @endif
+                                                                @endif
+                                                            </div>
+                                                        </div>
+                                                    </td>
+                                                    <td class="p-0 border-left border-right">
+                                                        <table class="table table-sm table-condensed border-0 mb-0">
+                                                            @if($claim->status !== 'CANCELLED')
+                                                                <thead>
+                                                                <tr class="">
+                                                                    <th colspan="3" class="border-top-0 border-bottom">
+                                                                        <div>
+                                                                <span moe class="d-block" title="Submit Claim">
+                                                                    <a class="" href="" show start>Generate Submission to Payer (1°)</a>
+                                                                    <form url="/api/mbClaim/createFromClaimForPrimaryPayer">
+                                                                        <input type="hidden" name="claimUid" value="{{$claim->uid}}">
+                                                                        <p>Generate Submission?</p>
+                                                                        <div class="mb-0">
+                                                                            <button class="btn btn-primary btn-sm" submit>Submit</button>
+                                                                            <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                                                                        </div>
+                                                                    </form>
+                                                                </span>
+                                                                        </div>
+                                                                    </th>
+                                                                </tr>
+                                                                </thead>
+                                                            @endif
+                                                            @if(count($claim->mbClaims))
+                                                                <thead>
+                                                                <tr class="bg-light">
+                                                                    <th class="border-0">Created</th>
+                                                                    <th class="border-0">Status</th>
+                                                                    <th class="border-0">&nbsp;</th>
+                                                                </tr>
+                                                                </thead>
+                                                                <tbody class="pb-3">
+                                                                @foreach($claim->mbClaims as $mbClaim)
+                                                                    <tr>
+                                                                        <td>
+                                                                            @if($mbClaim->claim_version_id !== $claim->current_version_id)
+                                                                                <i class="fa fa-exclamation-triangle text-warning-mellow text-sm" title="This submission was generated using an older version of the claim"></i>
+                                                                            @else
+                                                                                <i class="fa fa-asterisk text-secondary text-sm" title="This submission is up to date"></i>
+                                                                            @endif
+                                                                            <a native target="_blank"
+                                                                               open-in-stag-popup
+                                                                               title="Submission Details"
+                                                                               href="{{route('mb-claim', ['patient' => $patient, 'mbClaim' => $mbClaim])}}">
+                                                                                {{ friendlier_date_time($mbClaim->created_at) }}
+                                                                            </a>
+                                                                        </td>
+                                                                        <td>
+                                                                            {{$mbClaim->status}}
+                                                                            @if($mbClaim->status_memo)
+                                                                                <div class="font-italic text-secondary text-sm">{{$mbClaim->status_memo}}</div>
+                                                                            @endif
+                                                                        </td>
+                                                                        <td class="text-right pr-2">
+                                                                 <span moe relative title="Submit Claim">
+                                                                    <a class="" href="" show start><i class="fa fa-edit"></i></a>
+                                                                    <form url="/api/mbClaim/updateStatus" right>
+                                                                        <input type="hidden" name="uid" value="{{$mbClaim->uid}}">
+                                                                        <div class="form-group">
+                                                                            <label for="" class="control-label">Status</label>
+                                                                            <select name="status" class="form-control form-control-sm" required>
+                                                                                <option value="">-- select --</option>
+                                                                                <option value="NEW" {{$mbClaim->status === 'NEW' ? 'selected' : ''}}>New</option>
+                                                                                <option value="PROCESSING" {{$mbClaim->status === 'PROCESSING' ? 'selected' : ''}}>Processing</option>
+                                                                                <option value="SUBMITTED" {{$mbClaim->status === 'SUBMITTED' ? 'selected' : ''}}>Submitted</option>
+                                                                            </select>
+                                                                        </div>
+                                                                        <div class="form-group">
+                                                                            <label for="" class="control-label">Status Memo</label>
+                                                                            <textarea name="memo" class="form-control"></textarea>
+                                                                        </div>
+                                                                        <div class="mb-0">
+                                                                            <button class="btn btn-primary btn-sm" submit>Submit</button>
+                                                                            <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                                                                        </div>
+                                                                    </form>
+                                                                </span>
+                                                                            <a class="ml-1" target="_blank" native href="/api/mbClaim/downloadEDI/{{$mbClaim->uid}}" show start><i class="fa fa-file-download"></i></a>
+                                                                            <a class="ml-1 text-success" href="" show start><i class="fa fa-arrow-right"></i></a>
+                                                                        </td>
+                                                                    </tr>
+                                                                @endforeach
+                                                                </tbody>
+                                                            @else
+                                                                <tbody>
+                                                                <tr>
+                                                                    <td colspan="3">
+                                                                        <p class="p-1 text-secondary m-0">No submissions in this claim</p>
+                                                                    </td>
+                                                                </tr>
+                                                                </tbody>
+                                                            @endif
+                                                        </table>
+                                                    </td>
+                                                </tr>
+                                            @endif
+                                        @endforeach
+                                        </tbody>
+                                    </table>
+                                </div>
+                            @else
+                                <div class="screen-only my-3 px-3 d-flex">
+                                    <p class="font-weight-bold mb-0 text-secondary">No claims in this note</p>
+                                    @include('app/patient/note/_create-claim')
+                                </div>
+                            @endif
+                        @endif
+
+
+                        <div class="border-top p-3 screen-only">
+                            @if($note->addendums->count())
+                                <div class="">
+                                    <div class="d-flex align-items-center mb-2">
+                                        <p class="font-weight-bold text-secondary m-0">Addendums</p>
+                                        @include('app/patient/note/_create-addendum')
+                                    </div>
+                                    <table class="table table-sm tabe-striped border-left border-right border-bottom m-0">
+                                        <thead class="bg-light">
+                                        <tr>
+                                            <th class="border-bottom-0 pl-2 w-75">Addendum</th>
+                                            <th class="border-bottom-0">Created</th>
+                                            <th class="border-bottom-0 delete-column"></th>
+                                        </tr>
+                                        </thead>
+                                        <tbody>
+                                        @foreach ($note->addendums as $addendum)
+                                            <tr>
+                                                <td class="pl-2">{{ $addendum->memo }}</td>
+                                                <td class="">{{ friendly_date_time($addendum->created_at, false)}}</td>
+                                                <td>
+                                                    <div class="d-flex align-items-center">
+                                                        <div moe relative class="mr-2">
+                                                            <a href="" show start><i class="fa fa-pencil-alt"></i></a>
+                                                            <form url="/api/noteAddendum/updateMemo" right>
+                                                                <input type="hidden" name="uid" value="{{$addendum->uid}}">
+                                                                <div class="mb-2 d-block">
+                                                                    <label class="d-block text-sm text-secondary mb-1">Addendum</label>
+                                                                    <textarea class="form-control form-control-sm" name="memo" rows="5">{{$addendum->memo}}</textarea>
+                                                                </div>
+                                                                <div class="form-group mb-0">
+                                                                    <button class="btn btn-primary btn-sm mr-1" submit>Submit</button>
+                                                                    <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                                                                </div>
+                                                            </form>
+                                                        </div>
+                                                        <div moe relative class="mr-1">
+                                                            <a href="" show start class="text-danger"><i class="fa fa-trash"></i></a>
+                                                            <form url="/api/noteAddendum/remove" right>
+                                                                <input type="hidden" name="uid" value="{{$addendum->uid}}">
+                                                                <p>Remove this addendum?</p>
+                                                                <div class="form-group mb-0">
+                                                                    <button class="btn btn-danger btn-sm mr-1" submit>Yes</button>
+                                                                    <button class="btn btn-default border btn-sm" cancel>No</button>
+                                                                </div>
+                                                            </form>
+                                                        </div>
+                                                    </div>
+                                                </td>
+                                            </tr>
+                                        @endforeach
+                                        </tbody>
+                                    </table>
+                                </div>
+                            @else
+                                <div class="d-flex">
+                                    <p class="font-weight-bold mb-0 text-secondary">No addendums in this note</p>
+                                    @include('app/patient/note/_create-addendum')
+                                </div>
+                            @endif
+                        </div>
+
+                        <div class="screen-only">
+                            @include('app/patient/note/_cancel-signed-note')
+                        </div>
+
+
+                    </div>
+                </div>
+            </div>
+        </div>
+    </div>
+    <div class="note-templates-underlay"></div>
+    @include('app.patient.note.dashboard_script')
+    @include('app.patient.canvas-sections.canvas-editor-modal', ['key' => 'rx', 'class' => 'wide', 'noEditLink' => true])
+    <script>
+        (function() {
+            function init() {
+                fixTreeTopAndHeight();
+                $(window).on('resize', fixTreeTopAndHeight);
+                $(window).on('scroll', fixTreeTopAndHeight);
+                $('.note-tree-node>a[data-section-template-name]')
+                    .off('click.scroll-to-section')
+                    .on('click.scroll-to-section', function() {
+                         let section = $('div.note-section[data-section-template-name="' + $(this).attr('data-section-template-name') + '"]').first();
+                         if(section.length) {
+                             section[0].scrollIntoView({
+                                 behavior: "smooth",
+                                 block: "center",
+                                 inline: "center"
+                             });
+                             section.addClass('spot-highlight');
+                             setTimeout(() => {
+                                 section.removeClass('spot-highlight');
+                             }, 1500);
+                             $('.note-tree-node.active').removeClass('active');
+                             $(this).closest('.note-tree-node').addClass('active');
+                         }
+                         return false;
+                    });
+            }
+            function fixTreeTopAndHeight() {
+                let tree = $('#note-lhs-tree'), noteCardHeader = $('#note-card-header'),
+                    resultTop = (noteCardHeader.offset().top + noteCardHeader.outerHeight(true)) - $(window).scrollTop();
+                if(resultTop <= 55) {
+                    tree.addClass('fixed');
+                }
+                else {
+                    tree.removeClass('fixed');
+                    tree.css('height', 'calc(100vh - ' + resultTop + 'px)');
+                    tree.css('max-height', 'calc(100vh - ' + resultTop + 'px)');
+                }
+            }
+            addMCInitializer('note-tree', init, '#note-lhs-tree');
+        })();
+    </script>
+@endsection

File diff suppressed because it is too large
+ 857 - 805
resources/views/app/patient/note/dashboard.blade.php


+ 50 - 6
resources/views/app/patient/note/dashboard_script.blade.php

@@ -5,6 +5,34 @@
 
             function init() {
 
+                // on note-section hover, highlight the according left-tree node(s)
+                $(document)
+                    .off('mouseenter', '.note-section')
+                    .on('mouseenter', '.note-section', function(){
+                        $('.note-tree-node').removeClass('hovered');
+                        let target = $('.note-tree-node a[data-segment-uid="' + $(this).attr('data-segment-uid') + '"]');
+                        target.parent().addClass('hovered');
+                        target.parent().parents('.note-tree-node').addClass('hovered');
+                        return false;
+                    });
+
+                $(document)
+                    .off('mouseenter', '[data-non-segment-section]')
+                    .on('mouseenter', '[data-non-segment-section]', function(){
+                        $('.note-tree-node').removeClass('hovered');
+                        let target = $('.note-tree-node a[data-non-segment-target="' + $(this).attr('data-non-segment-section') + '"]');
+                        target.parent().addClass('hovered');
+                        target.parent().parents('.note-tree-node').addClass('hovered');
+                        return false;
+                    });
+
+                $(document)
+                    .off('mouseleave', '.note-section')
+                    .on('mouseleave', '.note-section', () => {
+                        $('.note-tree-node').removeClass('hovered');
+                        return false;
+                    });
+
                 // print note
                 $(document)
                     .off('click.print', '.print-note')
@@ -77,10 +105,24 @@
 
                 });
 
-                $('.edit-trigger')
-                    .off('click.edit-trigger')
-                    .on('click.edit-trigger', function() {
+                $(document)
+                    .off('click.edit-trigger', '.edit-trigger:not(.edit)')
+                    .on('click.edit-trigger', '.edit-trigger:not(.edit)', function() {
+
+                        if($('.note-section>.stag-popup:visible').length) return;
+
                         let editParent = $(this).closest('.note-section');
+
+                        // TEMP: disable edit mode for medrisk_vigilance
+                        // TODO: do this in the proper place
+                        if(editParent.is('[data-segment-template-name="medrisk_vigilence"]')) return false;
+
+                        // TEMP: open in popup if LS segment
+                        if(editParent.is('[data-segment-template-name^="lifestyle_"]')) {
+                            showStagPopup('segment-popup-' + editParent.attr('data-segment-template-name'), true);
+                            return false;
+                        }
+
                         if(editParent.is('.edit')) {
                             editParent.removeClass('edit');
                         }
@@ -289,6 +331,7 @@
                     return false;
                 });
 
+                @if(!$note->visitTemplate)
                 $(document)
                     .off('mousedown.enable-edit', '.note-section:not(.edit):not(.page-driven)')
                     .on('mousedown.enable-edit', '.note-section:not(.edit):not(.page-driven)', function(e) {
@@ -298,6 +341,7 @@
                         $(this).find('.edit-trigger').first().click();
                         return false;
                     });
+                @endif
 
                 // $(document)
                 //     .off('mousedown.enable-edit', '.note-section:not(.edit).page-driven')
@@ -335,12 +379,12 @@
                 });
 
                 // refresh once ticket popup is closed
-                $('body').off('stag-popup-closed')
+                /*$('body').off('stag-popup-closed')
                 $('body').on('stag-popup-closed', function() {
                     if($('#note-single-header').length) {
                         fastReload();
                     }
-                });
+                });*/
                 // ticket-popup
                 $(document)
                     .off('click', '.ticket-popup-trigger.note-dashboard-action')
@@ -458,6 +502,6 @@
                 $('.note-template-output-text:visible').first().html(lines.join(''));
             }
 
-            addMCInitializer('note-single', init);
+            addMCInitializer('note-single', init, '#note-single-header');
         })();
     </script>

+ 2 - 0
resources/views/app/patient/note/note-section-list.blade.php

@@ -1,3 +1,4 @@
+<div id="note-section-list">
 <?php $canvasData = json_decode($patient->canvas_data, true); ?>
 <?php $previousHeading = null; ?>
 @foreach($note->sections as $section)
@@ -24,4 +25,5 @@ if(!empty($previousHeading)) {
     echo '</div></div>'; // <!-- close any open parent section -->
 }
 ?>
+</div>
 @include('app.patient.note.section_script')

+ 8 - 0
resources/views/app/patient/note/note-segment-list.blade.php

@@ -0,0 +1,8 @@
+<div class="segments-list" id="note-segments-list">
+    @foreach($note->segments as $segment)
+        <div class="{{$segment->segmentTemplate->internal_name === 'medrisk_vigilence' ? 'd-none' : ''}}">
+            @include('app.patient.note.segment')
+        </div>
+    @endforeach
+</div>
+@include('app.patient.note.segment_script')

File diff suppressed because it is too large
+ 433 - 0
resources/views/app/patient/note/pdf.blade.php


+ 35 - 0
resources/views/app/patient/note/plan-log.blade.php

@@ -0,0 +1,35 @@
+<div class="p-3">
+    <?php $numPlans = 0; ?>
+    @foreach($point->childPlans as $record)
+        @if(@$record->data)
+            <?php $numPlans++; ?>
+            <div class="border mb-3">
+                <div class="border-bottom p-2">
+                    <span class="text-secondary text-sm">Created on: </span>
+                    <a native target="_blank" class="text-sm"
+                       href="<?= route('patients.view.notes.view.dashboard', ['patient' => $record->client, 'note' => $record->note]) ?>">
+                        <?= friendlier_date_time($record->created_at) ?>
+                    </a>
+                </div>
+                <div class="p-2">
+                    <?php
+                    if (file_exists(resource_path('views/app/patient/segment-templates/_plan/' . strtolower($record->parent_category) . '/view.php'))) {
+                        $plan = json_decode($record->data);
+                        include resource_path('views/app/patient/segment-templates/_plan/problem/view.php');
+                    } else {
+                        $plan = json_decode($record->data);
+                        echo $plan->value;
+                    }
+                    ?>
+                </div>
+            </div>
+        @endif
+    @endforeach
+    @if(!$numPlans)
+        <div class="border mb-3">
+            <div class="p-2">
+                No plans
+            </div>
+        </div>
+    @endif
+</div>

+ 35 - 0
resources/views/app/patient/note/review-log.blade.php

@@ -0,0 +1,35 @@
+<div class="p-3">
+    <?php $numReviews = 0; ?>
+    @foreach($point->childReviews as $record)
+        @if(@$record->data)
+            <?php $numReviews++; ?>
+            <div class="border mb-3">
+                <div class="border-bottom p-2">
+                    <span class="text-secondary text-sm">Reviewed on: </span>
+                    <a native target="_blank" class="text-sm"
+                       href="<?= route('patients.view.notes.view.dashboard', ['patient' => $record->client, 'note' => $record->note]) ?>">
+                        <?= friendlier_date_time($record->created_at) ?>
+                    </a>
+                </div>
+                <div class="p-2">
+                    <?php
+                    if (file_exists(resource_path('views/app/patient/segment-templates/_review/' . strtolower($record->parent_category) . '/view.php'))) {
+                        $review = json_decode($record->data);
+                        include resource_path('views/app/patient/segment-templates/_review/problem/view.php');
+                    } else {
+                        $review = json_decode($record->data);
+                        echo $review->value;
+                    }
+                    ?>
+                </div>
+            </div>
+        @endif
+    @endforeach
+    @if(!$numReviews)
+        <div class="border mb-3">
+            <div class="p-2">
+                No reviews
+            </div>
+        </div>
+    @endif
+</div>

+ 34 - 24
resources/views/app/patient/note/section.blade.php

@@ -4,7 +4,7 @@ if ($latestSectionTS === 0 || $latestSectionTS < $sectionTS) {
     $latestSectionTS = $sectionTS;
 }
 ?>
-<div data-ts="{{$sectionTS}}" class="p-3 border-bottom note-section {{ $section->sectionTemplate->is_page_driven ? 'page-driven' : '' }}"
+<div data-ts="{{$sectionTS}}" class="p-3 border-bottom note-section {{ $section->sectionTemplate->is_page_driven ? '' : '' }}"
     data-section-uid="{{ $section->uid }}"
     data-section-template-uid="{{ $section->sectionTemplate->uid }}"
     data-section-template-name="{{ $section->sectionTemplate->internal_name }}">
@@ -12,7 +12,7 @@ if ($latestSectionTS === 0 || $latestSectionTS < $sectionTS) {
         @if(!isset($note) || (isset($note) && !$note->is_signed_by_hcp))
             <a class="font-weight-bold mb-2 d-flex align-items-center c-pointer">
                 {{$section->sectionTemplate->title}}
-                @if(!isset($guestAccessCode) && !$section->sectionTemplate->is_page_driven)
+                @if(!isset($guestAccessCode) )
                     <span class="d-none if-not-edit"><i class="fa fa-edit ml-2"></i></span>
                     <span class="d-none if-edit edit-trigger font-weight-normal ml-2">Collapse</span>
                     <span class="edit-trigger"></span>
@@ -26,14 +26,14 @@ if ($latestSectionTS === 0 || $latestSectionTS < $sectionTS) {
         <?php $sectionInternalName = $section->sectionTemplate->internal_name; ?>
 
         @if($sectionInternalName === "exam" || $sectionInternalName === "objective")
-        @include('app/patient/note/_templates-exam-index')
+            @include('app/patient/note/_templates-exam-index')
         @else
-        @include('app/patient/note/_templates-index')
+            @include('app/patient/note/_templates-index')
         @endif
 
         @if (!$section->sectionTemplate->is_page_driven)
             @if (file_exists(storage_path('sections/' . $sectionInternalName . '/actions.php'))) {
-            <?php include(storage_path('sections/' . $sectionInternalName . '/actions.php')); ?>
+                <?php include(storage_path('sections/' . $sectionInternalName . '/actions.php')); ?>
             @elseif (file_exists(storage_path('sections/' . $sectionInternalName . '/actions.blade.php')))
                 @include('sections/' . $sectionInternalName . '/actions')
             @endif
@@ -71,35 +71,36 @@ if ($latestSectionTS === 0 || $latestSectionTS < $sectionTS) {
                     Remove
                 </a>
                 @if($pro->pro_type === 'ADMIN' || true)
-                <a href="#" class="d-none if-edit ml-2 move-up-trigger" data-uid="{{$section->uid}}" title="Move Up">
-                    <i class="fa fa-arrow-up"></i>
-                </a>
-                <a href="#" class="d-none if-edit ml-2 move-down-trigger" data-uid="{{$section->uid}}" title="Move Down">
-                    <i class="fa fa-arrow-down"></i>
-                </a>
+                    <a href="#" class="d-none if-edit ml-2 move-up-trigger" data-uid="{{$section->uid}}" title="Move Up">
+                        <i class="fa fa-arrow-up"></i>
+                    </a>
+                    <a href="#" class="d-none if-edit ml-2 move-down-trigger" data-uid="{{$section->uid}}" title="Move Down">
+                        <i class="fa fa-arrow-down"></i>
+                    </a>
                 @endif
             </div>
         @endif
     </div>
+
     @if(!isset($guestAccessCode) || $section->guest_access_level == 'READ')
-    <div class="{{isset($guestAccessCode)?'':'d-none'}} if-not-edit  inset-comment summary-container">
-        <?php if ($section->sectionTemplate->is_page_driven): ?>
-            @include("app.patient.page-sections.{$sectionInternalName}.summary")
-        <?php else: ?>
-            {!! !empty($section->summary_html) ? $section->summary_html : '-' !!}
-        <?php endif; ?>
-    </div>
+        <div class="{{isset($guestAccessCode)?'':'d-none'}} if-not-edit  inset-comment summary-container">
+            <?php if ($section->sectionTemplate->is_page_driven): ?>
+                @include("app.patient.page-sections.{$sectionInternalName}.summary")
+            <?php else: ?>
+                {!! !empty($section->summary_html) ? $section->summary_html : '-' !!}
+            <?php endif; ?>
+        </div>
     @endif
 
     @if(!$section->sectionTemplate->is_page_driven && (!isset($guestAccessCode) || $section->guest_access_level == 'WRITE'))
-    <div class="{{isset($guestAccessCode)?'':'d-none'}} if-edit">
+        <div class="{{isset($guestAccessCode)?'':'d-none'}} if-edit">
 
         <?php
         // if page
-        if ($section->sectionTemplate->is_page_driven) {
-        $contentData = false;
+            if ($section->sectionTemplate->is_page_driven) {
+                $contentData = false;
         ?>
-        @include("app.patient.page-sections.{$sectionInternalName}.form")
+            @include("app.patient.page-sections.{$sectionInternalName}.form")
         <?php
         }
         // if canvas
@@ -133,8 +134,8 @@ if ($latestSectionTS === 0 || $latestSectionTS < $sectionTS) {
             }
         ?>
             <input type="hidden" name="data">
-            <div note-rte data-content="{{$contentData['value']}}" class="form-group mb-2 border-left border-right rte-holder"></div>
-        <?php
+                <div note-rte data-content="{{$contentData['value']}}" class="form-group mb-2 border-left border-right rte-holder"></div>
+            <?php
         }
         ?>
 
@@ -145,4 +146,13 @@ if ($latestSectionTS === 0 || $latestSectionTS < $sectionTS) {
         </div>
     </div>
     @endif
+
+    @if($section->sectionTemplate->is_page_driven && (!isset($guestAccessCode) || $section->guest_access_level == 'WRITE'))
+        <div class="{{isset($guestAccessCode)?'':'d-none'}} if-edit">
+
+
+            @include("app.patient.page-sections.{$sectionInternalName}.form")
+
+        </div>
+    @endif
 </div>

+ 1 - 2
resources/views/app/patient/note/section_script.blade.php

@@ -174,7 +174,6 @@
                 if(_elem.closest('.note-section').is('.edit')) {
                     // console.log('ALIX: In edit mode. Auto-saving', _elem.closest('.note-section').attr('data-section-template-name'))
                     $('body').addClass('blocking-mode');
-                    showMoeFormMask('blocking-overlay');
                     doSave(_elem.closest('.note-section'));
                 }
                 else {
@@ -186,7 +185,7 @@
             });
         }
 
-        addMCInitializer('note-sections-list', init);
+        addMCInitializer('note-sections-list', init, '#note-section-list');
 
     })();
 </script>

+ 147 - 0
resources/views/app/patient/note/segment.blade.php

@@ -0,0 +1,147 @@
+<?php $iName = $segment->segmentTemplate->internal_name; ?>
+<div class="p-3 border-bottom note-section visit-segment {{$note->is_signed_by_hcp ? '' : 'edit-trigger'}} {{strpos($iName, 'lifestyle_') === 0 && $iName !== 'lifestyle_general' ? 'zero-height' : ''}}"
+     data-segment-uid="{{ $segment->uid }}"
+     data-segment-template-uid="{{ $segment->segmentTemplate->uid }}"
+     data-segment-template-name="{{ $segment->segmentTemplate->internal_name }}">
+
+    <?php $isLSSegment = strpos($iName, 'lifestyle_') === 0; ?>
+
+    <div class="d-flex align-items-baseline">
+
+        <!-- show hierarchy -->
+        {{--@if($segment->heading)
+            <span class="text-secondary">{{$segment->heading}}</span>
+            <i class="text-secondary text-sm fa fa-arrow-right mx-2"></i>
+        @endif
+        @if($segment->subheading)
+            <span class="text-secondary">{{$segment->subheading}}</span>
+            <i class="text-secondary text-sm fa fa-arrow-right mx-2"></i>
+        @endif--}}
+
+    <!-- title -->
+
+        @if($iName === 'medrisk_vigilence')
+            <div class="font-weight-bold text-center flex-grow-1">
+                <div class="on-hover-hide font-weight-normal text-info font-weight-bold text-center pt-2 font-size-11">MRV</div>
+                <span class="on-hover-only text-left">MedRisk Vigilence</span>
+            </div>
+        @else
+            <span class="font-weight-bold d-flex align-items-center {{$isLSSegment || $iName === 'medrisk_vigilence' ? '' : 'mb-2'}}">
+                @if($isLSSegment && $iName === 'lifestyle_general')
+                    Lifestyle
+                @else
+                    {{$segment->display_title}}
+                @endif
+
+                @if($segment->heading && $iName !== 'medrisk_vigilence')
+                    <span class="text-secondary ml-2 text-sm font-weight-normal">({{$segment->heading}})</span>
+                @endif
+            </span>
+        @endif
+
+        @if($isLSSegment)
+            @if($iName === 'lifestyle_general')
+                <a href="#" class="ls-segment-trigger ml-2" data-target="lifestyle_general">General</a>
+                <span class="mx-2 text-secondary text-sm">|</span>
+                <a href="#" class="ls-segment-trigger" data-target="lifestyle_nutrition">Nutrition</a>
+                <span class="mx-2 text-secondary text-sm">|</span>
+                <a href="#" class="ls-segment-trigger" data-target="lifestyle_physical_activity">Physical Act.</a>
+                <span class="mx-2 text-secondary text-sm">|</span>
+                <a href="#" class="ls-segment-trigger" data-target="lifestyle_sleep">Sleep</a>
+                <span class="mx-2 text-secondary text-sm">|</span>
+                <a href="#" class="ls-segment-trigger" data-target="lifestyle_social">Social Relns.</a>
+                <span class="mx-2 text-secondary text-sm">|</span>
+                <a href="#" class="ls-segment-trigger" data-target="lifestyle_substances">Subst. Use</a>
+                <span class="mx-2 text-secondary text-sm">|</span>
+                <a href="#" class="ls-segment-trigger" data-target="lifestyle_stress">Stress</a>
+            @else
+                <span class="text-info ml-auto font-weight-normal">(click to view)</span>
+            @endif
+        @endif
+
+        @if(!$note->is_signed_by_hcp && !$isLSSegment)
+            <a class="edit-trigger d-none if-edit c-pointer ml-3">
+                <i class="fas fa-caret-up font-size-16"></i>
+            </a>
+
+            <!-- refresh -->
+            <a class="ml-3 font-weight-normal refresh-segment c-pointer {{$iName === 'medrisk_vigilence' ? 'on-hover-only' : ''}}"
+               data-segment-uid="{{$segment->uid}}"
+               title="Update with latest patient data">
+                <i class="fa fa-sync"></i>
+            </a>
+
+            <!-- if intake - link to plan segment-->
+            <?php
+            $isIntake = strpos($iName, 'intake_') === 0;
+            ?>
+            @if($isIntake)
+                <?php
+                $targetSegment = 'plan_' . substr($iName, 7);
+                ?>
+                <a class="segment-trigger ml-3"
+                   href="#"
+                   data-target="{{$targetSegment}}">
+                    Changes During this Visit
+                </a>
+            @endif
+
+            <!-- if plan - link to intake segment-->
+            <?php
+            $isPlan = strpos($iName, 'plan_') === 0 && $iName !== 'plan_free_text';
+            ?>
+            @if($isPlan)
+                <?php
+                $targetSegment = 'intake_' . substr($iName, 5);
+                ?>
+                <a class="segment-trigger ml-3"
+                   href="#"
+                   data-target="{{$targetSegment}}">
+                    Back to Intake (Subjective)
+                </a>
+            @endif
+
+            @include('app/patient/note/_templates-v2-index', ['sectionInternalName' => $segment->segmentTemplate->internal_name])
+        @endif
+
+    </div>
+
+    <!-- popup hack for LS segments -->
+    <?php if(!$isLSSegment): ?>
+
+    <div class="d-none if-not-edit inset-comment summary-container {{$iName === 'medrisk_vigilence' ? 'px-0' : ''}}">
+        {!! $segment->summary_html !!}
+    </div>
+
+    <div class="d-none if-edit edit-container">
+        {!! $segment->edit_html !!}
+    </div>
+
+    <?php endif ?>
+
+    <!-- popup hack for LS segments -->
+    <?php if($isLSSegment): ?>
+    <div class="stag-popup stag-popup-md"
+         stag-popup-key="segment-popup-<?= $segment->segmentTemplate->internal_name ?>">
+        <div class="stag-popup-content">
+            <h3 class="stag-popup-title m-neg-3 px-3 mt-0 pb-3 border-bottom mb-3 pt-1">
+                <span class="d-inline-flex align-items-center">
+                    @if($segment->subheading)
+                        {{$segment->subheading}}
+                        <i class="text-secondary text-sm fa fa-arrow-right mx-2"></i>
+                    @endif
+                    {{$segment->display_title}}
+                </span>
+                <a href="#" class="ml-auto text-secondary" onclick="event.stopPropagation(); return closeStagPopup()">
+                    <i class="fa fa-times-circle"></i>
+                </a>
+            </h3>
+            <div class="ls-segment-edit-html">
+                {!! $segment->edit_html !!}
+            </div>
+        </div>
+    </div>
+    <?php endif ?>
+
+</div>
+

+ 369 - 0
resources/views/app/patient/note/segment_script.blade.php

@@ -0,0 +1,369 @@
+<script>
+    (function() {
+
+        function updateAllSegmentsInResponse(_response, _updateListeners = true) {
+            if(!hasResponseError(_response)) {
+
+                // refresh primary segment (where uid is _response.data.uid)
+                if(_response.data && _response.data.uid) {
+                    updateSegmentByUid(_response.data.uid, _response.data.summaryHtml, _response.data.editHtml);
+                }
+
+                // refresh listening segments
+                if(_updateListeners) {
+                    if(_response.data && _response.data.listenerSegmentUids && _response.data.listenerSegmentUids.length) {
+                        for (let i=0; i<_response.data.listenerSegmentUids.length; i++) {
+                            let listenerSegment = $('.note-section[data-segment-uid="' + _response.data.listenerSegmentUids[i] + '"]');
+                            let listenerSegmentTemplateName = listenerSegment.attr('data-segment-template-name');
+                            if(listenerSegment && listenerSegment.length) {
+                                $.post('/api/visit/updateSegmentHtml', {
+                                    segmentUid: _response.data.listenerSegmentUids[i]
+                                }, _data => {
+                                    updateAllSegmentsInResponse(_data, false);
+
+                                    // ugly hack!
+                                    if(listenerSegmentTemplateName === 'medrisk_vigilence') {
+                                        $('.mrv-trigger')
+                                            .empty()
+                                            .append('<div class="text-info font-weight-bold text-center font-size-11">MRV</div>')
+                                            .append(_data.data.summaryHtml);
+                                    }
+
+                                }, 'json');
+                            }
+                        }
+                    }
+                }
+            }
+        }
+
+        function updateSegmentByUid(_uid, _summaryHtml, _editHtml) {
+            let segment = $('.note-section[data-segment-uid="' + _uid + '"]');
+            if(segment && segment.length) {
+                segment.find('.summary-container').html(_summaryHtml);
+                segment.find('.edit-container').html(_editHtml);
+
+                // special case for lifestyle
+                let popupContainer = $('[stag-popup-key="segment-popup-' + segment.attr('data-segment-template-name') + '"] .ls-segment-edit-html');
+                if(popupContainer.length) {
+                    popupContainer.html(_editHtml);
+                }
+
+                initRTEs(segment);
+                initSegmentMoes(segment);
+                initMoes();
+                initStagSuggest();
+                if(window.segmentInitializers) {
+                    let internalName = segment.attr('data-segment-template-name');
+                    if(window.segmentInitializers.hasOwnProperty(internalName) &&
+                        typeof window.segmentInitializers[internalName] === 'function') {
+                        window.segmentInitializers[internalName].call(window);
+                    }
+                }
+            }
+        }
+
+        function updateSegmentFromObject(_object) {
+            let segment = $('.note-section[data-segment-uid="' + _object.segmentUid + '"]');
+            if(segment && segment.length) {
+                segment.find('.summary-container').html(_object.summaryHtml);
+                segment.find('.edit-container').html(_object.editHtml);
+                initRTEs(segment);
+                initSegmentMoes(segment);
+                initMoes();
+                initStagSuggest();
+                if(window.segmentInitializers) {
+                    let internalName = segment.attr('data-segment-template-name');
+                    if(window.segmentInitializers.hasOwnProperty(internalName) &&
+                        typeof window.segmentInitializers[internalName] === 'function') {
+                        window.segmentInitializers[internalName].call(window);
+                    }
+                }
+            }
+        }
+
+        window.autoSaveSegment = function(_trigger) {
+            saveVisitForm(_trigger, true);
+        };
+
+        window.autoSaveSegmentAndClose = function(_trigger) {
+            saveVisitForm(_trigger, true, true);
+        };
+
+        function saveVisitForm(_trigger, _silent = false, _close = false) {
+            let form = $(_trigger).closest('form');
+
+            if (!_silent && !form[0].checkValidity()) {
+                form[0].reportValidity();
+                return false;
+            }
+
+            // add [data-name] values to payload
+            let dataField = form.find('[name="data"]').first();
+            let parsed = null;
+            if(dataField.val()) {
+                parsed = JSON.parse(dataField.val());
+            }
+            form.find('[data-name]').each(function() {
+                if(!parsed) parsed = {};
+
+                let keys = $(this).attr('data-name').split('->');
+                let currentNode = parsed;
+                for (let i = 0; i < keys.length; i++) {
+                    if(i !== keys.length - 1) {
+                        if(typeof currentNode[keys[i]] === 'undefined') {
+                            currentNode[keys[i]] = {};
+                        }
+                        currentNode = currentNode[keys[i]];
+                    }
+                    else {
+                        if($(this).is(':checkbox')) {
+                            currentNode[keys[i]] = $(this).prop('checked');
+                        }
+                        else {
+                            currentNode[keys[i]] = $(this).val();
+                        }
+                    }
+                }
+
+            });
+            if(parsed) {
+                dataField.val(JSON.stringify(parsed));
+            }
+
+            if(!_silent) showMask();
+
+            let closeOnSave = false, noteSection = form.closest('.note-section');
+            if($(_trigger).closest('[visit-moe]').is('[close-on-save]')) {
+                closeOnSave = true;
+            }
+
+            $.post(form.attr('url'), form.serialize(), _data => {
+                if(!hasResponseError(_data)) {
+                    if(!_silent) {
+                        hideMask();
+                        updateAllSegmentsInResponse(_data);
+                        if (closeOnSave) {
+                            noteSection.removeClass('edit');
+                            let segmentUid = form.find('[name="segmentUid"]').first();
+                            segmentUid = segmentUid.length ? segmentUid.val() : false;
+                            if (segmentUid) {
+                                window.setTimeout(() => {
+                                    $('.note-tree-node>a[data-segment-uid="' + segmentUid + '"]').trigger('click');
+                                }, 250);
+                            }
+                        }
+                    }
+                    if(_close) {
+                        closeStagPopup();
+                    }
+                }
+            }, 'json');
+            return false;
+        }
+
+        function initSegmentMoes(_parent) {
+
+            $('body')
+                .off('mousedown.visit-moe-outside-click')
+                .on('mousedown.visit-moe-outside-click', function (e) {
+                    if ($(e.target).closest('[visit-moe]').length) {
+                        return;
+                    }
+                    $('[visit-moe] [url]:not([show])').hide();
+                });
+
+            _parent.find('[visit-moe] [submit]')
+                .off('click.visit-moe-submit')
+                .on('click.visit-moe-submit', function() {
+                    saveVisitForm(this);
+                    return false;
+                });
+
+            _parent.find('[visit-moe]>a[start]')
+                .off('click.visit-moe-show')
+                .on('click.visit-moe-show', function () {
+                    $('[visit-moe] [url]:not([show])').hide();
+                    $(this)
+                        .closest('[visit-moe]')
+                        .find('form[url]')
+                        .show();
+                    return false;
+                });
+
+            _parent.find('[visit-moe] [cancel]')
+                .off('click.visit-moe-cancel')
+                .on('click.visit-moe-cancel', function() {
+                    $(this).closest('[visit-moe]').find('[url]:not([show])').hide();
+                    if($(this).closest('[visit-moe]').is('[close-on-cancel]')) {
+                        $(this).closest('.note-section').removeClass('edit');
+                    }
+                    return false;
+                });
+        }
+
+        function initRTEs(_parent) {
+            _parent.find('[note-rte]:not(.ql-container)').each(function() {
+
+                $(this).wrap(
+                    $('<div class="border-left border-right rte-holder"/>')
+                        .attr('data-shortcuts', '')
+                );
+
+                // give a unique id to this editor instance
+                var editorID = Math.ceil(Math.random() * 99999),
+                    fieldName = $(this).attr('data-field-name') ? $(this).attr('data-field-name') : 'free_text';
+
+                var el = this;
+                var existingContent = $(el).html();
+                var quill = new Quill(el, {
+                    theme: 'snow',
+                    modules: stagQuillConfig
+                });
+
+                var toolbar = $(quill.container).prev('.ql-toolbar');
+
+                // add button for new shortcut
+                var newSCButton = $('<button class="btn bg-white btn-sm btn-default text-primary w-auto px-2 border py-0 ' +
+                    'text-sm add-shortcut" data-editor-id="' + editorID + '">+ Shortcut</button>');
+                toolbar.append(newSCButton);
+
+                quill.root.innerHTML = existingContent;
+
+                quill.on('text-change', function(delta, oldDelta, source) {
+                    var content = quill.root.innerHTML;
+                    let dataObject = {};
+                    dataObject[fieldName] = content;
+                    var dataValue = JSON.stringify(dataObject);
+                    $(el).closest('.note-section').find('input[name=data]').val(dataValue);
+                });
+
+                $(quill.container)
+                    .find('.ql-editor[contenteditable]')
+                    .attr('data-field', fieldName)
+                    .attr('data-editor-id', editorID)
+                    .attr('with-shortcuts', 1);
+            });
+        }
+
+        function init() {
+
+            $(document)
+                .off('input.auto-grow', '[visit-moe] form textarea')
+                .on('input.auto-grow', '[visit-moe] form textarea', function() {
+                    this.style.minHeight = "calc(1.5em + .5rem + 2px)";
+                    this.style.height = "calc(1.5em + .5rem + 2px)";
+                    this.style.height = (this.scrollHeight)+"px";
+                });
+
+            let parent = $('.segments-list');
+            initRTEs(parent);
+            initSegmentMoes(parent);
+            initStagSuggest();
+
+            // check and run all segment initializers
+            try {
+                if(window.segmentInitializers) {
+                    for(let x in window.segmentInitializers) {
+                        if(window.segmentInitializers.hasOwnProperty(x) && typeof window.segmentInitializers[x] === 'function') {
+                            window.segmentInitializers[x].call(window);
+                        }
+                    }
+                }
+            }
+            catch (e) {
+                console.warn('Error running 1 or more segment initializers.')
+            }
+
+            // refresh segment
+            $(document)
+                .off('click.refresh-segment', '.refresh-segment')
+                .on('click.refresh-segment', '.refresh-segment', function() {
+                    showMask();
+                    $.post('/api/visit/updateSegmentHtml', {
+                        segmentUid: $(this).attr('data-segment-uid')
+                    }, _data => {
+                        hideMask();
+                        updateAllSegmentsInResponse(_data);
+                    }, 'json');
+                    return false;
+                });
+
+            // ls segment special vase
+            $(document)
+                .off('click.ls-segment-trigger', '.ls-segment-trigger[data-target]')
+                .on('click.ls-segment-trigger', '.ls-segment-trigger[data-target]', function() {
+                    $('.note-section.edit-trigger[data-segment-template-name="' + $(this).attr('data-target') + '"]').trigger('click');
+                    return false;
+                });
+
+            // link to other segments by internal_name
+            $(document)
+                .off('click.segment-trigger', '.segment-trigger[data-target]')
+                .on('click.segment-trigger', '.segment-trigger[data-target]', function() {
+                    $('.note-tree-node [data-segment-internal-name="' + $(this).attr('data-target') + '"]').trigger('click');
+                    return false;
+                });
+
+            /*
+            $('[btn-save-form]').on('click', function() {
+                doSave($(this).closest('.note-section'));
+            });
+
+            @if(isset($guestAccessCode))
+                $('.note-section form').append("<input type='hidden' name='guest_access_code' value='{{$guestAccessCode}}'/>");
+            @endif
+
+            // copy link
+            $(document)
+                .off('click.copy', '.copy-link')
+                .on('click.copy', '.copy-link', function() {
+                    var copyText = $('#' + $(this).attr('data-id'));
+                    copyText.focus().select();
+                    document.execCommand("copy");
+                    toastr.success("The link " + copyText.val() + " has been copied to the clipboard");
+                    return false;
+                });
+
+            // [name="data"] change listener
+            $('.note-section input[name="data"], .note-section input[name="items"]').each(function() {
+                initChangeListener($(this));
+            });
+             */
+
+            // relevance
+            $(document).off('change', '.visit-segment[data-segment-template-name] .chk-relevance');
+            $(document).on('change', '.visit-segment[data-segment-template-name] .chk-relevance', function () {
+                let segment = $(this).closest('.visit-segment');
+                if(this.checked) {
+                    $.post('/api/visitPoint/markPointRelevantToNote', {
+                        noteUid: '{{$note->uid}}',
+                        pointUid: $(this).attr('data-point-uid')
+                    }, _data => {
+                        if(!hasResponseError(_data)) {
+                            segment.find('.refresh-segment').trigger('click');
+                        }
+                    }, 'json');
+                }
+                else {
+                    if($(this).attr('data-rel-uid')) {
+                        $.post('/api/visitPoint/undoMarkPointRelevantToNote', {
+                            uid: $(this).attr('data-rel-uid')
+                        }, _data => {
+                            if(!hasResponseError(_data)) {
+                                segment.find('.refresh-segment').trigger('click');
+                            }
+                        }, 'json');
+                    }
+                    else {
+                        console.log('Error - missing rel uid');
+                    }
+                }
+                return false;
+            });
+        }
+
+        addMCInitializer('note-segments-list', init, '#note-segments-list');
+
+    })();
+</script>

+ 199 - 0
resources/views/app/patient/note/sign-confirmation.blade.php

@@ -0,0 +1,199 @@
+<div class="mt-3 p-3 border-top min-height-500px" id="note-sign-confirmation-{{$note->id}}">
+    <p class="mb-2 font-weight-bold font-size-13 text-secondary">Visit Information</p>
+    <div class="pl-3 border-left">
+        <div class="mb-2 d-flex align-items-baseline">
+            <span class="width-150px">New or Follow-up visit:</span>
+            @if($note->new_or_fu_or_na === "NEW")
+                <b class="mr-3 width-70px">New</b>
+                <div moe relative>
+                    <a href="#" start show>Change to <b>Follow-up</b></a>
+                    <form url="/api/note/updateNewOrFuOrNa">
+                        <p class="text-nowrap">Change to <b>Follow-up</b> visit?</p>
+                        <input type="hidden" name="uid" value="{{$note->uid}}">
+                        <input type="hidden" name="newOrFuOrNa" value="FU">
+                        <div class="mb-0">
+                            <button class="btn btn-primary btn-sm" submit>Submit</button>
+                            <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                        </div>
+                    </form>
+                </div>
+            @elseif($note->new_or_fu_or_na === "FU")
+                <b class="mr-3 width-70px">Follow-up</b>
+                <div moe relative>
+                    <a href="#" start show>Change to <b>New</b></a>
+                    <form url="/api/note/updateNewOrFuOrNa">
+                        <p class="text-nowrap">Change to <b>New</b> visit?</p>
+                        <input type="hidden" name="uid" value="{{$note->uid}}">
+                        <input type="hidden" name="newOrFuOrNa" value="NEW">
+                        <div class="mb-0">
+                            <button class="btn btn-primary btn-sm" submit>Submit</button>
+                            <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                        </div>
+                    </form>
+                </div>
+            @endif
+        </div>
+        <div class="mb-2 d-flex align-items-baseline">
+        <span class="width-150px">Visit Method:</span>
+        @if(!!$note->method)
+            <b class="mr-3 text-capitalize width-70px">{{strtolower(str_replace("_", " ", $note->method))}}</b>
+        @else
+            <span class="mr-3 text-danger width-70px">(not set)</span>
+        @endif
+        <div moe relative>
+            <a href="" show start>Change</a>
+            <form url="/api/note/updateMethod">
+                <input type="hidden" name="uid" value="{{$note->uid}}">
+                <div class="mb-2">
+                    <select name="method" class="form-control form-control-sm note-method-select" required>
+                        <option value="AUDIO" {{ $note->method === "AUDIO" ? "selected" : "" }}>Audio</option>
+                        <option value="VIDEO" {{ $note->method === "VIDEO" ? "selected" : "" }}>Video</option>
+                        <option value="IN_CLINIC" {{ $note->method === "IN_CLINIC" ? "selected" : "" }}>In-Clinic</option>
+                        <option value="HOUSE_CALL" {{ $note->method === "HOUSE_CALL" ? "selected" : "" }}>House Call</option>
+                    </select>
+                </div>
+                <div class="form-group if-in-clinic">
+                    <label for="" class="text-secondary text-sm mb-1">Location</label>
+                    <select name="hcpCompanyLocationUid" class="form-control">
+                        <option value=""></option>
+                        @foreach($note->hcpPro->companyLocations() as $location)
+                            <option value="{{$location->uid}}" {{$location->id === $note->hcp_company_location_id ? 'selected' : ''}}>{{$location->line1}} {{$location->city}}</option>
+                        @endforeach
+                    </select>
+                </div>
+                <div class="mb-0">
+                    <button class="btn btn-primary btn-sm" submit>Submit</button>
+                    <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                </div>
+            </form>
+        </div>
+    </div>
+        <div class="mb-2 d-flex align-items-baseline">
+            <span class="width-150px">Visit Date:</span>
+            @if(!!$note->effective_dateest)
+                <b class="mr-3 text-capitalize width-70px">{{friendly_date_time($note->effective_dateest, false, '')}}</b>
+            @else
+                <span class="mr-3 text-danger width-70px">(not set)</span>
+            @endif
+            <div moe relative>
+                <a href="" show start>Change</a>
+                <form url="/api/note/putEffectiveDateEST">
+                    <input type="hidden" name="uid" value="{{$note->uid}}">
+                    <div class="mb-2">
+                        <label for="" class="text-secondary text-sm">Effective date EST</label>
+                        <input type="date" name="effectiveDateEST" value="{{$note->effective_dateest}}" class="form-control form-control-sm">
+                    </div>
+                    <div class="mb-0">
+                        <button class="btn btn-primary btn-sm" submit>Submit</button>
+                        <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                    </div>
+                </form>
+            </div>
+        </div>
+    </div>
+
+    @if($patient->mcp_pro_id === $pro->id && !$patient->has_cm_setup_been_performed)
+    <hr class="m-neg-3">
+    <p class="mb-2 font-weight-bold font-size-13 text-secondary">CCM</p>
+    <div class="pl-3 border-left">
+        <div class="mb-2">
+            <i class="fa fa-exclamation-triangle text-warning-mellow"></i>
+            WARNING: You are the MCP and patient is not currently enrolled in CCM.
+        </div>
+        <div class="mb-2">Would you like to mark them as enrolled?</div>
+        <div moe class="d-block">
+            <a href="" show start><b>Yes, mark as enrolled</b></a>
+            <form url="/api/note/markCmSetupPerformedAsMcp">
+                <input type="hidden" name="uid" value="{{$note->uid}}">
+                <p>Mark as enrolled in CCM?</p>
+                <div class="mb-0">
+                    <button class="btn btn-primary btn-sm" submit>Submit</button>
+                    <button class="btn btn-default border btn-sm" cancel>Cancel</button>
+                </div>
+            </form>
+        </div>
+    </div>
+    @endif
+
+    {{-- get problems(plan) and medications(plan) segments --}}
+    <?php
+    $problemsPlan = null;
+    $medicationsPlan = null;
+    foreach($note->segments as $segment) {
+        if($segment->segmentTemplate->internal_name === 'plan_problems') {
+            $problemsPlan = $segment;
+        }
+        if($segment->segmentTemplate->internal_name === 'plan_medications') {
+            $medicationsPlan = $segment;
+        }
+        if($problemsPlan && $medicationsPlan) break;
+    }
+    ?>
+    @if($problemsPlan)
+        <hr class="m-neg-3">
+        <p class="mb-2 font-weight-bold font-size-13 text-secondary">Problems (Plan)</p>
+        <div class="pl-3 border-left">
+            <div>{!! $problemsPlan->summary_html !!}</div>
+        </div>
+    @endif
+    @if($problemsPlan)
+        <hr class="m-neg-3">
+        <p class="mb-2 font-weight-bold font-size-13 text-secondary">Medications (Plan)</p>
+        <div class="pl-3 border-left">
+            <div>{!! $medicationsPlan->summary_html !!}</div>
+        </div>
+    @endif
+
+    <hr class="m-neg-3">
+    <p class="my-3">After signing - you will not be able to modify content. You may only add addendums.</p>
+
+    <div class="d-flex align-items-center justify-content-center">
+        <button class="btn btn-success btn-sm font-weight-bold px-3 btn-sign">Sign</button>
+        <button class="ml-3 btn btn-default border btn-sm px-3" onclick="return closeStagPopup()">Close</button>
+    </div>
+
+</div>
+
+<script>
+    (function() {
+
+        function init() {
+
+            if($('.relevant-without-review.block-signing[data-target-segment]').length) {
+                alert('Review missing for one or more problems relevant to this note!');
+                closeStagPopup(true);
+                $('.note-tree-node [data-segment-internal-name="' + $('.relevant-without-review.block-signing[data-target-segment]').first().attr('data-target-segment') + '"]').trigger('click');
+                return false;
+            }
+
+            if($('.relevant-without-plan.block-signing[data-target-segment]').length) {
+                alert('Plan missing for one or more problems relevant to this note!');
+                closeStagPopup(true);
+                $('.note-tree-node [data-segment-internal-name="' + $('.relevant-without-plan.block-signing[data-target-segment]').first().attr('data-target-segment') + '"]').trigger('click');
+                return false;
+            }
+
+            if($('.no-relevant-with-icd.block-signing[data-target-segment]').length) {
+                alert('Need at least 1 relevant problem with an ICD before the note can be signed.');
+                closeStagPopup(true);
+                $('.note-tree-node [data-segment-internal-name="' + $('.no-relevant-with-icd.block-signing[data-target-segment]').first().attr('data-target-segment') + '"]').trigger('click');
+                return false;
+            }
+
+            $('#note-sign-confirmation-{{$note->id}} .btn-sign')
+                .off('click')
+                .on('click', function() {
+                    $.post('/api/note/signAsHcp', {uid: '{{$note->uid}}'}, _data => {
+                        if(!hasResponseError(_data)) {
+                            toastr.success('Note signed');
+                            closeStagPopup();
+                        }
+                    }, 'json');
+                    return false;
+                });
+        }
+
+        addMCInitializer('note-sign-confirmation-{{$note->id}}', init, '#note-sign-confirmation-{{$note->id}}')
+
+    }).call(window);
+</script>

+ 110 - 70
resources/views/app/patient/notes.blade.php

@@ -2,84 +2,102 @@
 
 @section('inner-content')
 
+    <div id="notes-list-{{$patient->id}}">
     <div class="pt-2 d-flex align-items-start">
         <h6 class="my-0 text-secondary d-flex align-items-center w-100">
             <span class="font-weight-bold text-secondary">Notes</span>
-            <span class="mx-2 text-secondary">|</span>
-            <div moe>
-                <a start show class="py-0 mb-3">Add</a>
-                <form url="/api/note/create" class="mcp-theme-1"
-                      redir="patients/view/{{ $patient->uid }}/notes/view/[data]">
-                    <input type="hidden" name="clientUid" value="{{$patient->uid}}">
-                    <div class="form-group">
-                        <label for="" class="text-secondary text-sm mb-1">Pro *</label>
-                        <select name="hcpProUid" class="form-control" provider-search required data-pro-uid="{{$pro->is_hcp ? $pro->uid : ''}}">
-                        </select>
-                    </div>
-                    <input type="hidden" name="effectiveDateEST" value="{{ date('Y-m-d') }}">
-                    <div class="form-group">
-                        <label for="" class="text-secondary text-sm mb-1">Type *</label>
-                        <select name="newOrFuOrNa" class="form-control">
-                            <option value="NEW">New Patient</option>
-                            <option value="FU">Follow Up</option>
-                            <option value="NA">N/A</option>
-                        </select>
-                    </div>
-                    <div class="form-group">
-                        <label for="" class="text-secondary text-sm mb-1">Method *</label>
-                        <select name="method" class="form-control note-method-select" required>
-                            <option value="">-- select --</option>
-                            <option value="VIDEO">Video</option>
-                            <option value="AUDIO">Audio</option>
-                            <option value="IN_CLINIC">In Clinic</option>
-                            <option value="HOUSE_CALL">House Call</option>
-                        </select>
-                    </div>
-                    <div class="form-group if-in-clinic">
-                        <label for="" class="text-secondary text-sm mb-1">Location</label>
-                        <select name="hcpCompanyLocationUid" class="form-control">
-                            <option value=""></option>
-                            @foreach($pro->companyLocations() as $location)
-                                <option value="{{$location->uid}}">{{$location->line1}} {{$location->city}}</option>
-                            @endforeach
-                        </select>
-                    </div>
-                    <div>
-                        <button submit class="btn btn-sm btn-primary mr-1">Submit</button>
-                        <button cancel class="btn btn-sm btn-default border">Cancel</button>
-                    </div>
-                </form>
-            </div>
-            <span class="mx-2 text-secondary">|</span>
-            <div moe>
-                <a start show class="py-0 mb-3">Add (univ) *</a>
-                <form url="/api/note/createUsingTemplateWithPages"
+            @if($patient->getPrimaryCoverageStatus() === 'YES')
+                <span class="mx-2 text-secondary">|</span>
+                <div moe>
+                    <a start show class="py-0 mb-3">Add</a>
+
+
+                    <form url="/api/note/createUsingTemplate"
+                          redir="/patients/view/{{$patient->uid}}/notes/view/[data]"
+                          class="mcp-theme-1">
+                        <input type="hidden" name="clientUid" value="{{$patient->uid}}">
+                        <input type="hidden" name="effectiveDateEST" value="{{date("Y-m-d")}}">
+                        <input type="hidden" name="effectiveTime" value="{{date("h:i")}}">
+                        <input type="hidden" name="title" id="note-create-title" value="">
+                        <div class="form-group mb-2">
+                            <label for="" class="text-secondary text-sm mb-1">Pro *</label>
+                            <select name="hcpProUid" class="form-control" provider-search required data-pro-uid="{{$pro->is_hcp ? $pro->uid : ''}}">
+                            </select>
+                        </div>
+                        <div class="form-group mb-2">
+                            <label for="" class="text-secondary text-sm mb-1">Note Template *</label>
+                            <select name="noteTemplateUid" class="form-control form-control-sm"
+                                    onchange="$('#note-create-title').val($(this).find('option:selected').text())"
+                                    required>
+                                <option value=""> --select--</option>
+                                @foreach($pro->noteTemplates as $noteTemplate)
+                                    <?php $nT = $noteTemplate->template(); ?>
+                                    <option value="{{$nT->uid}}">{{$nT->title}}</option>
+                                @endforeach
+                            </select>
+                        </div>
+                        <div class="mb-2">
+                            <label for="" class="text-secondary text-sm mb-1">Method *</label>
+                            <select name="method" class="form-control form-control-sm note-method-select" required>
+                                <option value="AUDIO">Audio</option>
+                                <option value="VIDEO">Video</option>
+                                <option value="IN_CLINIC">In-Clinic</option>
+                                <option value="HOUSE_CALL">House Call</option>
+                            </select>
+                        </div>
+                        <div class="form-group if-in-clinic">
+                            <label for="" class="text-secondary text-sm mb-1">Location</label>
+                            <select name="hcpCompanyLocationUid" class="form-control">
+                                <option value=""></option>
+                                @foreach($pro->companyLocations() as $location)
+                                    <option value="{{$location->uid}}">{{$location->line1}} {{$location->city}}</option>
+                                @endforeach
+                            </select>
+                        </div>
+                        <div class="form-group m-0">
+                            <button submit class="btn btn-primary btn-sm">submit</button>
+                        </div>
+                    </form>
+                </div>
+                <span class="mx-2 text-secondary">|</span>
+                <div moe>
+                <a start show class="py-0 mb-3 text-info font-weight-bold">Add Visit</a>
+                <form url="/api/visit/create"
                       redir="/patients/view/{{$patient->uid}}/notes/view/[data]"
                       class="mcp-theme-1">
                     <input type="hidden" name="clientUid" value="{{$patient->uid}}">
-                    @if($pro->is_hcp)
-                    <input type="hidden" name="hcpProUid" value="{{$pro->uid}}">
-                    @else
+                    @if($pro->isDefaultNA())
                     <input type="hidden" name="naProUid" value="{{$pro->uid}}">
                     @endif
-                    <input type="hidden" name="effectiveDateEST" value="{{date("Y-m-d")}}">
+                    <input type="hidden" name="effectiveDate" value="{{date("Y-m-d")}}">
                     <input type="hidden" name="effectiveTime" value="{{date("h:i")}}">
-                    <input type="hidden" name="title" id="note-create-title" value="">
+                    <input type="hidden" class="form-control form-control-sm" placeholder="title" name="title" id="note-create-title" value="Note">
+                    <div class="form-group">
+                        <label for="" class="text-secondary text-sm mb-1">HCP Pro *</label>
+                        <select name="hcpProUid" class="form-control" provider-search required data-pro-uid="{{$pro->is_hcp ? $pro->uid : ''}}">
+                        </select>
+                    </div>
                     <div class="form-group mb-2">
                         <label for="" class="text-secondary text-sm mb-1">Note Template *</label>
-                        <select name="noteTemplateUid" class="form-control form-control-sm"
+                        <select name="visitTemplateUid" class="form-control form-control-sm"
                                 onchange="$('#note-create-title').val($(this).find('option:selected').text())"
                                 required>
                             <option value=""> --select--</option>
-                            @foreach($pro->noteTemplates as $noteTemplate)
-                                <?php $nT = $noteTemplate->template(); ?>
-                                <option value="{{$nT->uid}}">{{$nT->title}}</option>
+                            @foreach($pro->visitTemplates() as $visitTemplate)
+                                <option value="{{$visitTemplate->uid}}">{{$visitTemplate->title}}</option>
                             @endforeach
                         </select>
                     </div>
+                    <div class="mb-2">
+                        <label for="" class="text-secondary text-sm mb-1">New/Fu</label>
+                        <select name="newOrFuOrNa" class="form-control form-control-sm note-method-select" required>
+                            <option value="NEW">New</option>
+                            <option value="FU">Follow-Up</option>
+                        </select>
+                    </div>
                     <div class="mb-2">
                         <label for="" class="text-secondary text-sm mb-1">Method *</label>
-                        <select name="method" class="form-control form-control-sm note-method-select" required>
+                        <select name="noteContactMethod" class="form-control form-control-sm note-method-select" required>
                             <option value="AUDIO">Audio</option>
                             <option value="VIDEO">Video</option>
                             <option value="IN_CLINIC">In-Clinic</option>
@@ -100,6 +118,16 @@
                     </div>
                 </form>
             </div>
+            @else
+                <span class="ml-3 text-danger">
+                    <i class="fa fa-exclamation-triangle"></i>
+                    <b>Cannot create note.</b> Patient is not covered or coverage is pending verification.
+                </span>
+                @if($pro->pro_type == 'ADMIN')
+                    <a class="ml-3" href="{{route('patients.view.client-primary-coverages', ['patient' => $patient])}}">View Coverages</a>
+                @endif
+            @endif
+
             <select class="ml-auto max-width-300px form-control form-control-sm"
                     onchange="fastLoad('/patients/view/{{$patient->uid}}/notes/' + this.value, true, false, false)">
                 <option value="active" {{ $filter === 'active' ? 'selected' : '' }}>Active notes</option>
@@ -115,10 +143,13 @@
             <th class="px-2 text-secondary border-bottom-0">Effective Date</th>
             <th class="px-2 text-secondary border-bottom-0">New Patient / FU</th>
             @if($pro->pro_type == 'ADMIN')
-		<th class="px-2 text-secondary border-bottom-0">Method</th>
-	    @endif
+                <th class="px-2 text-secondary border-bottom-0">Method</th>
+            @endif
             <th class="px-2 text-secondary border-bottom-0">HCP</th>
-            <th class="px-2 text-secondary border-bottom-0">Signed</th>
+            @if($pro->pro_type == 'ADMIN')
+                <th class="px-2 text-secondary border-bottom-0">NA</th>
+            @endif
+            <th class="px-2 text-secondary border-bottom-0">HCP Signed</th>
             <!-- <th class="px-2 text-secondary border-bottom-0 w-50">Content</th> -->
             <th class="px-2 text-secondary border-bottom-0">&nbsp;</th>
             <th class="px-2 text-secondary border-bottom-0">Actions</th>
@@ -142,22 +173,30 @@
         @foreach ($records as $note)
             <tr class="{{ $note->is_cancelled ? 'cancelled-item always-clickable' : '' }}">
                 <td class="px-2">
-                    <span class="font-weight-bold">
+                    <a href="/patients/view/{{ $patient->uid }}/notes/view/{{ $note->uid }}" class="font-weight-bold">
                         {{ friendly_date_time($note->effective_dateest, false) }}
-                    </span>
+                    </a>
+                    @if(!!$note->visitTemplate)
+                        <span class="text-info font-weight-bold">*</span>
+                    @endif
                     <span class="ml-1">{{ $note->is_cancelled ? '[cancelled]' : '' }}</span>
                 </td>
                 <td class="px-2">
                     {{ $note->new_or_fu_or_na === 'NEW' ? 'New Patient' : $note->new_or_fu_or_na }}
                 </td>
-		@if($pro->pro_type == 'ADMIN')
-		<td class="px-2">
-		    {{ $note->method }}
-		</td>
-		@endif
+                @if($pro->pro_type == 'ADMIN')
+                    <td class="px-2">
+                        {{ $note->method }}
+                    </td>
+                @endif
                 <td class="px-2">
                     {{$note->hcpPro ? $note->hcpPro->name_display: '-'}}
                 </td>
+                @if($pro->pro_type == 'ADMIN')
+                <td class="px-2">
+                    {{$note->allyPro ? $note->allyPro->name_display: '-'}}
+                </td>
+                @endif
                 <td class="px-2">
                     {!! $note->hcpPro && $note->is_signed_by_hcp ? '<b class="text-success">Yes</b>' : 'No' !!}
                 </td>
@@ -189,6 +228,7 @@
         @endforeach
         </tbody>
     </table>
+    </div>
     <script>
         (function() {
             function initNotesList() {
@@ -244,7 +284,7 @@
                     }
                 });
             }
-            addMCInitializer('notes-list', initNotesList);
+            addMCInitializer('notes-list', initNotesList, '#notes-list-{{$patient->id}}');
         })();
     </script>
 @endsection

+ 78 - 0
resources/views/app/patient/page-sections/cc/form.blade.php

@@ -0,0 +1,78 @@
+<?php
+
+use App\Models\Page;
+
+$page = Page::where('note_id', $note->id)->where('category', 'CHIEF_COMPLAINT')->first();
+
+
+$contentData = [
+    'value'=>''
+];
+
+if($page){
+    $contentData = json_decode($page->data, true);
+}
+?>
+<div id="ccSection">
+    <div class="form-group mb-2">
+        <input type="hidden" name="data" id="cc-data">
+        <div note-rte note-rte-ros data-content="{{isset($contentData['value'])?$contentData['value']:'' }}" class="form-group mb-2 border-left border-right rte-holder"></div>
+    </div>
+    <div class="form-group mb-2">
+        <button class="btn btn-sm btn-outline-primary" @click="save">Submit</button>
+    </div>
+</div>
+
+<script>
+    (function() {
+        function init() {
+            window.clientVitalsApp = new Vue({
+                el: '#ccSection',
+                data: {
+                    value: '',
+                },
+                mounted: function() {
+                    $(this.$el).closest('#ccSection').find('[name="data"]').val(this.value);
+                },
+                watch: {
+                    value: {
+                        handler: function(val, oldVal) {
+                            $(this.$el).closest('#ccSection').find('[name="data"]').val(this.value);
+                        },
+                        deep: true
+                    },
+                },
+                methods: {
+
+                    save: function(){
+                        console.log(this.value);
+                        showMask();
+                        console.log("DATA", this.value);
+
+                        var payload = {
+                            noteUid:  '{{$note->uid}}',
+                            parentPageUid: null,
+                            clientUid: '{{$patient->uid}}',
+                            category: 'CHIEF_COMPLAINT',
+                            key: null,
+                            data: $(this.$el).closest('#ccSection').find('[name="data"]').val()
+                        }
+                        console.log("PAYLOAD:  ", payload);
+                        $.post('/api/page/changeOrCreateNoteScoped', payload, _data => {
+                            if(!hasResponseError(_data)) {
+                                toastr.success('Medication updated!');
+                                closeStagPopup();
+                            }
+                        }, 'json');
+                        hideMask();
+                        fastReload();
+                        return false;
+
+                    }
+                }
+            });
+        }
+        addMCInitializer('client-cc', init, '#ccSection');
+    })();
+</script>
+

+ 23 - 0
resources/views/app/patient/page-sections/cc/summary.php

@@ -0,0 +1,23 @@
+<?php
+
+use App\Models\Page;
+
+$page = Page::where('note_id', $note->id)->where('category', 'CHIEF_COMPLAINT')->first();
+
+$contentData = [
+    'value'=>''
+];
+if($page && $page->data){
+    $contentData = json_decode($page->data, true);
+}
+
+?>
+
+<?php if(!$page): ?>
+    <div>No CC data</div>
+<?php else: ?>
+    <div class="d-flex">
+        <div><?php echo $contentData['value'] ?></div>
+    </div>
+<?php endif; ?>
+

+ 121 - 0
resources/views/app/patient/page-sections/rx/form.blade.php

@@ -0,0 +1,121 @@
+<?php
+
+use App\Models\Page;
+
+$medicationsAddedOnIntake = Page::where('client_id', $patient->id)
+    ->where('category', 'MEDICATION')
+    ->whereRaw("(is_active IS TRUE AND added_during_note_uid = ? AND added_reason_category = 'ADDED_ON_INTAKE') ",[$note->uid])
+    ->get();
+
+$medicationsRemovedOnIntake = Page::where('client_id', $patient->id)
+    ->where('category', 'MEDICATION')
+    ->whereRaw("(is_active IS FALSE AND deactivated_during_note_uid  = ? AND deactivation_reason_category = 'REMOVED_ON_INTAKE')", [$note->uid])
+    ->get();
+
+
+?>
+<div id="medicationSection">
+    <table>
+        <thead>
+        <tr>
+            <th>Medication</th>
+            <th></th>
+            <th></th>
+            <th></th>
+        </tr>
+        </thead>
+        @foreach($medicationsAddedOnIntake as $medOnIntake)
+        <tr>
+            <td>{{$medOnIntake->key }}</td>
+            <td>Dose</td>
+            <td>Route</td>
+            <td>Frequency</td>
+            <td>Description</td>
+            <td></td>
+        </tr>
+        @endforeach
+        <tr>
+            <td>
+                <input type="text" v-model="currentMed.name" placeholder="name">
+            </td>
+            <td>
+                <input type="text" v-model="currentMed.dose" placeholder="dose">
+            </td>
+            <td>
+                <input type="text" v-model="currentMed.route" placeholder="route">
+            </td>
+            <td>
+                <input type="text" v-model="currentMed.frequency" placeholder="frequency">
+            </td>
+            <td>
+                <input type="text" v-model="currentMed.description" placeholder="description">
+            </td>
+            <td>
+                <button class="btn btn-sm btn-outline-primary" @click="save">Submit</button>
+            </td>
+        </tr>
+    </table>
+</div>
+
+<script>
+    (function() {
+        function init() {
+            window.clientVitalsApp = new Vue({
+                el: '#medicationSection',
+                data: {
+                    value: '',
+                    currentMed: {
+                        name:'',
+                        dose:'',
+                        route:'',
+                        frequency:'',
+                        description:''
+                    }
+                },
+                mounted: function() {
+                    $(this.$el).closest('#medicationSection').find('[name="data"]').val(this.value);
+                },
+                watch: {
+                    value: {
+                        handler: function(val, oldVal) {
+                            $(this.$el).closest('#medicationSection').find('[name="data"]').val(this.value);
+                        },
+                        deep: true
+                    },
+                },
+                methods: {
+
+                    save: function(){
+                        console.log(this.value);
+                        showMask();
+                        console.log("DATA", this.value);
+                        this.currentMed.isActive = true;
+                        this.currentMed.addedReasonCategory = 'ADDED_ON_INTAKE'; // ADDED_BY_HCP_DURING_NOTE, ADDED_ON_INTAKE;
+                        this.currentMed.addedReasonCategoryMemo = 'added on intake';
+                        var payload = {
+                            noteUid:  '{{$note->uid}}',
+                            parentPageUid: null,
+                            clientUid: '{{$patient->uid}}',
+                            category: 'MEDICATION',
+                            key: this.currentMed.name,
+                            data: JSON.stringify(this.currentMed)
+                        }
+                        console.log("PAYLOAD:  ", payload);
+                        $.post('/api/page/changeOrCreateClientScoped', payload, _data => {
+                            if(!hasResponseError(_data)) {
+                                toastr.success('Medication updated!');
+                                closeStagPopup();
+                            }
+                        }, 'json');
+                        hideMask();
+                        fastReload();
+                        return false;
+
+                    }
+                }
+            });
+        }
+        addMCInitializer('client-medication', init, '#medicationSection');
+    })();
+</script>
+

+ 45 - 0
resources/views/app/patient/page-sections/rx/summary.php

@@ -0,0 +1,45 @@
+<?php
+
+use App\Models\Page;
+
+$medicationsAddedOnIntake = Page::where('client_id', $patient->id)
+    ->where('category', 'MEDICATION')
+    ->whereRaw("(is_active IS TRUE AND  added_reason_category = 'ADDED_ON_INTAKE') ") //TODO fix query
+    ->get();
+
+$medicationsRemovedOnIntake = Page::where('client_id', $patient->id)
+    ->where('category', 'MEDICATION')
+    ->whereRaw("(is_active IS FALSE AND deactivated_during_note_uid  = ? AND deactivation_reason_category = 'REMOVED_ON_INTAKE')", [$note->uid])
+    ->get();
+
+?>
+
+<?php if(!count($medicationsAddedOnIntake)): ?>
+    <div>No medications</div>
+<?php else: ?>
+    <div><h1><?php echo count($medicationsAddedOnIntake); ?></h1></div>
+    <div class="d-flex">
+        <table>
+            <thead>
+            <tr>
+                <th>Medication</th>
+                <th>Dose</th>
+                <th>Route</th>
+                <th>Frequency</th>
+                <th></th>
+            </tr>
+            </thead>
+            <?php foreach($medicationsAddedOnIntake as $medOnIntake): ?>
+            <tr>
+                <td><?php echo $medOnIntake->key ?></td>
+                <td><?php echo $medOnIntake->data_dose ?></td>
+                <td><?php echo $medOnIntake->data_route ?></td>
+                <td><?php echo $medOnIntake->data_frequency ?></td>
+                <td></td>
+            </tr>
+            <?php endforeach; ?>
+
+        </table>
+    </div>
+<?php endif; ?>
+

+ 78 - 0
resources/views/app/patient/page-sections/subjective/form.blade.php

@@ -0,0 +1,78 @@
+<?php
+
+use App\Models\Page;
+
+$page = Page::where('note_id', $note->id)->where('category', 'SUBJECTIVE_GENERAL')->first();
+
+
+$contentData = [
+    'value'=>''
+];
+
+if($page){
+    $contentData = json_decode($page->data, true);
+}
+?>
+<div id="subjectiveSection">
+    <div class="form-group mb-2">
+        <input type="hidden" name="data" id="subjective-data">
+        <div note-rte note-rte-ros data-content="{{isset($contentData['value'])?$contentData['value']:'' }}" class="form-group mb-2 border-left border-right rte-holder"></div>
+    </div>
+    <div class="form-group mb-2">
+        <button class="btn btn-sm btn-outline-primary" @click="save">Submit</button>
+    </div>
+</div>
+
+<script>
+    (function() {
+        function init() {
+            window.clientVitalsApp = new Vue({
+                el: '#subjectiveSection',
+                data: {
+                    value: '',
+                },
+                mounted: function() {
+                    $(this.$el).closest('#subjectiveSection').find('[name="data"]').val(this.value);
+                },
+                watch: {
+                    value: {
+                        handler: function(val, oldVal) {
+                            $(this.$el).closest('#subjectiveSection').find('[name="data"]').val(this.value);
+                        },
+                        deep: true
+                    },
+                },
+                methods: {
+
+                    save: function(){
+                        console.log(this.value);
+                        showMask();
+                        console.log("DATA", this.value);
+
+                        var payload = {
+                            noteUid:  '{{$note->uid}}',
+                            parentPageUid: null,
+                            clientUid: '{{$patient->uid}}',
+                            category: 'SUJECTIVE_GENERAL',
+                            key: null,
+                            data: $(this.$el).closest('#subjectiveSection').find('[name="data"]').val()
+                        }
+                        console.log("PAYLOAD:  ", payload);
+                        $.post('/api/page/changeOrCreateNoteScoped', payload, _data => {
+                            if(!hasResponseError(_data)) {
+                                toastr.success('Record updated!');
+                                closeStagPopup();
+                            }
+                        }, 'json');
+                        hideMask();
+                        fastReload();
+                        return false;
+
+                    }
+                }
+            });
+        }
+        addMCInitializer('client-subjective', init, '#subjectiveSection');
+    })();
+</script>
+

+ 23 - 0
resources/views/app/patient/page-sections/subjective/summary.php

@@ -0,0 +1,23 @@
+<?php
+
+use App\Models\Page;
+
+$page = Page::where('note_id', $note->id)->where('category', 'SUBJECTIVE_GENERAL')->first();
+
+$contentData = [
+    'value'=>''
+];
+if($page && $page->data){
+    $contentData = json_decode($page->data, true);
+}
+
+?>
+
+<?php if(!$page): ?>
+    <div>No Subject data</div>
+<?php else: ?>
+    <div class="d-flex">
+        <div><?php echo $contentData['value'] ?></div>
+    </div>
+<?php endif; ?>
+

+ 20 - 0
resources/views/app/patient/page-sections/vitals/default.php

@@ -0,0 +1,20 @@
+<?php
+
+
+use App\Models\Page;
+
+$page = Page::where('client_id', $patient->id)->where('category', 'VITALS')->first();
+
+$contentData = [];
+
+if($page){
+    $contentData = json_decode($page->data, true);
+}else{
+    if ($patient->canvas_data) {
+        $canvasData = json_decode($patient->canvas_data, true);
+        if (isset($canvasData["vitals"])) {
+            $contentData = $canvasData["vitals"];
+        }
+    }
+}
+

+ 264 - 0
resources/views/app/patient/page-sections/vitals/form.blade.php

@@ -0,0 +1,264 @@
+<?php
+
+use App\Models\Page;
+
+$page = Page::where('note_id', $note->id)->where('category', 'VITALS')->first();
+
+$contentData = [];
+
+if($page){
+    $contentData = json_decode($page->data, true);
+}
+
+$vitalLabels = [
+    "heightInInches" => "Ht. (in.)",
+    "weightPounds" => "Wt. (lbs.)",
+    "temperatureF" => "Temp. (F)",
+    "systolicBP" => "SBP",
+    "diastolicBP" => "DBP",
+    "pulseRatePerMinute" => "Pulse",
+    "respirationRatePerMinute" => "Resp.",
+    "pulseOx" => "Pulse Ox.",
+    "smokingStatus" => "Smoking Status",
+    "bmi" => "BMI (kg/m²)",
+];
+if(!$contentData) {
+    $contentData = [
+        "heightInInches" => [
+            "label" => "Ht. (in.)",
+            "value" => "",
+            "date" => "",
+        ],
+        "weightPounds" => [
+            "label" => "Wt. (lbs.)",
+            "value" => "",
+            "date" => "",
+        ],
+        "temperatureF" => [
+            "label" => "Temp. (F)",
+            "value" => "",
+            "date" => "",
+        ],
+        "systolicBP" => [
+            "label" => "SBP",
+            "value" => "",
+            "date" => "",
+        ],
+        "diastolicBP" => [
+            "label" => "DBP",
+            "value" => "",
+            "date" => "",
+        ],
+        "pulseRatePerMinute" => [
+            "label" => "Pulse",
+            "value" => "",
+            "date" => "",
+        ],
+        "respirationRatePerMinute" => [
+            "label" => "Resp.",
+            "value" => "",
+            "date" => "",
+        ],
+        "pulseOx" => [
+            "label" => "Pulse Ox.",
+            "value" => "",
+            "date" => "",
+        ],
+        "smokingStatus" => [
+            "label" => "Smoking Status",
+            "value" => "",
+            "date" => "",
+        ],
+        "bmi" => [
+            "label" => "BMI (kg/m²)",
+            "value" => "",
+            "date" => "",
+        ],
+    ];
+}
+else {
+    // ensure $contentData has all the expected vitals and correct labels!
+    foreach ($vitalLabels as $k => $v) {
+        if(!isset($contentData[$k])) {
+            $contentData[$k] = [
+                "label" => $v,
+                "value" => "",
+                "date" => "",
+            ];
+        }
+    }
+}
+
+$formID = rand(0, 100000);
+?>
+<div id="vitalsSection">
+    <h3 class="stag-popup-title mb-2 border-bottom-0 pb-1 hide-if-note">
+        <span>Vitals</span>
+        <a href="#" onclick="return closeStagPopup()"
+           class="ml-auto text-secondary">
+            <i class="fa fa-times-circle"></i>
+        </a>
+    </h3>
+
+    <input type="hidden" name="data" value="{{json_encode($contentData)}}">
+
+    <table class="table table-sm table-bordered mb-2 table-edit-sheet">
+        <thead>
+        <tr class="bg-light">
+            <th class="px-2 text-secondary border-bottom-0 w-25">Vital</th>
+            <th class="px-2 text-secondary border-bottom-0 w-35">Value</th>
+            <th class="px-2 text-secondary border-bottom-0">Date</th>
+        </tr>
+        </thead>
+        <tbody>
+            @foreach($vitalLabels as $k => $v)
+                <tr>
+                    <td>
+                        <input type="text" tabindex="-1"
+                               class="form-control form-control-sm events-none"
+                               data-field="title" value="{{ $v }}" readonly>
+                    </td>
+                    <td class="position-relative">
+                        @if($k === "bmi")
+                            <input type="text" readonly
+                                   class="form-control form-control-sm vitals-title"
+                                   data-field="value" v-model="bmi">
+                            <p class="py-1 m-0 px-2 font-weight-bold bg-white" v-if="!!bmi">
+                                <span class="text-sm text-warning-mellow" v-if="+bmi < 18.5">Underweight</span>
+                                <span class="text-sm text-success" v-if="+bmi >= 18.5 && +bmi < 25">Healthy Weight</span>
+                                <span class="text-sm text-warning-mellow" v-if="+bmi >= 25 && +bmi < 30">Overweight</span>
+                                <span class="text-sm text-warning-mellow" v-if="+bmi >= 30">Obese</span>
+                            </p>
+                        @elseif($k === "smokingStatus")
+                            <input type="text"
+                                   class="form-control form-control-sm"
+                                   data-field="value" v-model="items['smokingStatus'].value"
+                                   data-option-list="smokingStatus"
+                                   v-on:change="autoDate(items['smokingStatus'], 'smokingStatus')" v-on:keyup="autoDate(items['smokingStatus'], 'smokingStatus')">
+                            <div id="smoking-status-options" class="data-option-list">
+                                <div>Current</div>
+                                <div>Former</div>
+                                <div>Never</div>
+                            </div>
+                        @else
+                            <input type="text"
+                                   class="form-control form-control-sm"
+                                   data-field="value" v-model="items['{{ $k }}'].value"
+                                   v-on:change="autoDate(items['{{ $k }}'], '{{ $k }}')" v-on:keyup="autoDate(items['{{ $k }}'], '{{ $k }}')">
+                        @endif
+                    </td>
+                    <td>
+                        <input type="date" {{ $k === 'bmi' ? 'readonly' : '' }}
+                               class="form-control form-control-sm vitals-title"
+                               data-field="date" v-model="items['{{ $k }}'].date">
+                    </td>
+                </tr>
+
+            @endforeach
+        </tbody>
+    </table>
+    <div>
+        <button class="btn btn-sm btn-outline-primary" @click="save">Submit</button>
+    </div>
+</div>
+<script>
+    (function() {
+        function init() {
+            window.clientVitalsApp = new Vue({
+                el: '#vitalsSection',
+                data: {
+                    today: '{{ date("Y-m-d") }}',
+                    items: <?= json_encode($contentData) ?>,
+                    itemsOriginal: <?= json_encode($contentData) ?>
+                },
+                mounted: function() {
+                    $(this.$el).closest('#vitalsSection').find('[name="data"]').val(
+                        JSON.stringify(this.cleanObject(this.items))
+                    );
+                },
+                watch: {
+                    items: {
+                        handler: function(val, oldVal) {
+                            $(this.$el).closest('#vitalsSection').find('[name="data"]').val(
+                                JSON.stringify(this.cleanObject(this.items))
+                            );
+                        },
+                        deep: true
+                    },
+                },
+                computed: {
+                    bmi: function () {
+                        let result = '';
+                        let h = this.items.heightInInches, w = this.items.weightPounds;
+                        if(!h || !w) {
+                            return result;
+                        }
+                        h = h.value;
+                        w = w.value;
+                        try {
+                            h = parseFloat(h);
+                            w = parseFloat(w);
+                            if(!h || !w) {
+                                this.items.bmi.value = '';
+                                return result;
+                            }
+                            let result = (w / [ h * h]) * 703;
+                            return result.toFixed(1);
+                        }
+                        catch (e) {
+                            return result;
+                        }
+                    }
+                },
+                methods: {
+                    autoDate: function(_item, _index) {
+                        console.log('ALIX autoDate for', _index)
+                        if((_item.value !== this.itemsOriginal[_index].value) && !_item.date) {
+                            _item.date = this.today;
+                        }
+                    },
+                    cleanObject: function(_source) {
+                        let plObject = {};
+                        for (let y in _source) {
+                            if(_source.hasOwnProperty(y)) {
+                                plObject[y] = _source[y];
+                            }
+                        }
+                        plObject.bmi = {
+                            label: "BMI (kg/m²)",
+                            value: this.bmi,
+                            date: this.bmi ? this.today : '',
+                        };
+                        return plObject;
+                    },
+                    save: function(){
+                        console.log(this.items);
+                        showMask();
+                        console.log("DATA", this.items);
+
+                        var payload = {
+                             noteUid:  '{{$note->uid}}',
+                             parentPageUid: null,
+                             clientUid: '{{$patient->uid}}',
+                             category: 'VITALS',
+                             key: null,
+                             data: JSON.stringify(this.items)
+                        }
+                        console.log("PAYLOAD:  ", payload);
+                        $.post('/api/page/changeOrCreateNoteScoped', payload, _data => {
+                            if(!hasResponseError(_data)) {
+                                toastr.success('Record updated!');
+                                closeStagPopup();
+                            }
+                        }, 'json');
+                        hideMask();
+                        fastReload();
+                        return false;
+
+                    }
+                }
+            });
+        }
+        addMCInitializer('client-vitals', init, '#vitalsSection');
+    })();
+</script>

+ 131 - 0
resources/views/app/patient/page-sections/vitals/summary.php

@@ -0,0 +1,131 @@
+<?php
+
+use App\Models\Page;
+
+$page = Page::where('note_id', $note->id)->where('category', 'VITALS')->first();
+$vitalLabels = [
+    "heightInInches" => "Ht. (in.)",
+    "weightPounds" => "Wt. (lbs.)",
+    "temperatureF" => "Temp. (F)",
+    "systolicBP" => "SBP",
+    "diastolicBP" => "DBP",
+    "pulseRatePerMinute" => "Pulse",
+    "respirationRatePerMinute" => "Resp.",
+    "pulseOx" => "Pulse Ox.",
+    "smokingStatus" => "Smoking Status",
+    "bmi" => "BMI (kg/m²)",
+];
+$contentData = [
+    "heightInInches" => [
+        "label" => "Ht. (in.)",
+        "value" => "",
+        "date" => "",
+    ],
+    "weightPounds" => [
+        "label" => "Wt. (lbs.)",
+        "value" => "",
+        "date" => "",
+    ],
+    "temperatureF" => [
+        "label" => "Temp. (F)",
+        "value" => "",
+        "date" => "",
+    ],
+    "systolicBP" => [
+        "label" => "SBP",
+        "value" => "",
+        "date" => "",
+    ],
+    "diastolicBP" => [
+        "label" => "DBP",
+        "value" => "",
+        "date" => "",
+    ],
+    "pulseRatePerMinute" => [
+        "label" => "Pulse",
+        "value" => "",
+        "date" => "",
+    ],
+    "respirationRatePerMinute" => [
+        "label" => "Resp.",
+        "value" => "",
+        "date" => "",
+    ],
+    "pulseOx" => [
+        "label" => "Pulse Ox.",
+        "value" => "",
+        "date" => "",
+    ],
+    "smokingStatus" => [
+        "label" => "Smoking Status",
+        "value" => "",
+        "date" => "",
+    ],
+    "bmi" => [
+        "label" => "BMI (kg/m²)",
+        "value" => "",
+        "date" => "",
+    ],
+];
+
+
+if($page){
+    $contentData = json_decode($page->data, true);
+}else{
+    if($patient->canvas_data) {
+        $canvasData = json_decode($patient->canvas_data, true);
+        if(isset($canvasData["vitals"])) {
+            $contentData = $canvasData["vitals"];
+            // ensure $contentData has all the expected vitals and correct labels!
+        }
+    }
+}
+
+foreach ($vitalLabels as $k => $v) {
+    if(!isset($contentData[$k])) {
+        $contentData[$k] = [
+            "label" => $v,
+            "value" => "",
+            "date" => "",
+        ];
+    }
+}
+
+foreach ($vitalLabels as $k => $v) {
+?>
+    <div class="d-flex vital-item align-items-center">
+        <span class="content-html text-nowrap">
+            <span><?= $v ?>:</span>
+            <?php
+            $vital = [];
+            if(isset($contentData[$k])) {
+                $vital = $contentData[$k];
+            }
+            ?>
+            <b><?= isset($vital["value"]) && !empty($vital["value"]) ? $vital["value"] : '-' ?></b>
+            <?php if($k === 'bmi' && isset($vital["value"]) && !empty($vital["value"])):
+                $bmi = floatval($vital["value"]);
+                ?>
+                <span class="ml-2 py-1 m-0 font-weight-bold">
+                    <?php if($bmi < 18.5): ?>
+                        <span class="text-sm text-warning-mellow">(Underweight)</span>
+                    <?php endif; ?>
+                    <?php if($bmi >= 18.5 && $bmi < 25): ?>
+                        <span class="text-sm text-success">(Healthy Weight)</span>
+                    <?php endif; ?>
+                    <?php if($bmi >= 25 && $bmi < 30): ?>
+                        <span class="text-sm text-warning-mellow">(Overweight)</span>
+                    <?php endif; ?>
+                    <?php if($bmi >= 30): ?>
+                        <span class="text-sm text-warning-mellow">(Obese)</span>
+                    <?php endif; ?>
+                </span>
+            <?php endif; ?>
+            <?php if(!!$vital["date"]): ?>
+                <span class="font-weight-normal text-secondary ml-2 text-sm">(as on <?= friendly_date_time($vital["date"], false) ?>)</span>
+            <?php endif; ?>
+        </span>
+    </div>
+<?php
+}
+?>

+ 9 - 2
resources/views/app/patient/partials/appointment-confirmation-history.blade.php

@@ -7,7 +7,14 @@ $cDecisions = $appointment->confirmationDecisions;
     <p class="my-2"><b>Requests</b></p>
     @foreach($cRequests as $cRequest)
         <div class="bg-light p-1 my-1 border border">
-            <div class="text-nowrap">{{ friendly_date_time($cRequest->created_at) }} to <b>{{ $cRequest->to_sms_number }}</b> (SMS)</div>
+            <div class="text-nowrap">{{ friendly_date_time($cRequest->created_at) }} to:
+                @if($cRequest->to_sms_number)
+                    <div class="text-sm"><i class="fa fa-sms text-secondary"></i> {{ $cRequest->to_sms_number }}</div>
+                @endif
+                @if($cRequest->to_email_address)
+                    <div class="text-sm"><i class="fa fa-envelope text-secondary"></i> {{ $cRequest->to_email_address }}</div>
+                @endif
+            </div>
             <div class="text-secondary text-sm on-hover-text-reveal">{{ $cRequest->message }}</div>
         </div>
     @endforeach
@@ -17,7 +24,7 @@ $cDecisions = $appointment->confirmationDecisions;
     <p class="my-2"><b>Decisions</b></p>
     @foreach($cDecisions as $cDecision)
         <div class="bg-light p-1 my-1 border border">
-            <b class="{{$cDecision->accepted_or_rejected === 'ACCEPTED' ? 'text-success' : 'text-warning-mellow'}}">{{$cDecision->accepted_or_rejected}}</b> on {{ friendly_date_time($cDecision->created_at) }}
+            <b class="{{$cDecision->accepted_or_rejected_or_waived === 'ACCEPTED' ? 'text-success' : 'text-warning-mellow'}}">{{$cDecision->accepted_or_rejected_or_waived}}</b> on {{ friendly_date_time($cDecision->created_at) }}
             @if($cDecision->memo)
                 <div class="text-sm">
                     <i>{{$cDecision->memo}}</i>

+ 2 - 2
resources/views/app/patient/partials/appointment-confirmation.blade.php

@@ -1,4 +1,4 @@
-<div class="d-flex">
+<div class="d-flex" id="appointment-confirmation">
     <div class="flex-grow-1">
         @if($appointment->status === 'CREATED' && !$appointment->latest_confirmation_request_at && !$appointment->latest_confirmation_decision_at)
             <b class="text-warning-mellow">Not requested yet</b>
@@ -65,6 +65,6 @@
                     container.load('/appointment-confirmation-history/' + $(this).attr('data-uid'));
                 });
         }
-        addMCInitializer('appointment-confirmation', init);
+        addMCInitializer('appointment-confirmation', init, '#appointment-confirmation');
     }).call(window);
 </script>

+ 6 - 2
resources/views/app/patient/partials/appointment-request-confirmation.blade.php

@@ -1,10 +1,14 @@
 <div moe relative class="">
     <a href="#" start show class="text-sm font-weight-normal">{{ $label }}</a>
-    <form url="/api/appointment/sendConfirmationRequestViaSms" right>
+    <form url="/api/appointment/sendConfirmationRequestViaEmailAndSms" right>
         <input type="hidden" name="uid" value="{{ $appointment->uid }}">
         <div class="mb-2">
             <label for="" class="text-sm text-secondary mb-1">Cell Number</label>
-            <input type="text" class="form-control form-control-sm" name="toSmsNumber" value="{{$patient->cell_number}}" required>
+            <input type="text" class="form-control form-control-sm" name="toSmsNumber" value="{{$patient->cell_number}}">
+        </div>
+        <div class="mb-2">
+            <label for="" class="text-sm text-secondary mb-1">Email Address</label>
+            <input type="text" class="form-control form-control-sm" name="emailAddress" value="{{$patient->email_address}}">
         </div>
         <div>
             <button submit class="btn btn-sm btn-primary mr-1">Send</button>

+ 126 - 0
resources/views/app/patient/partials/latest-vitals.blade.php

@@ -0,0 +1,126 @@
+<?php
+
+use App\Models\Point;
+
+$category = 'VITALS';
+$endPoint = 'upsertNoteSingleton';
+
+$vitalLabels = [
+    "heightInInches" => "Ht. (in.)",
+    "weightPounds" => "Wt. (lbs.)",
+    "temperatureF" => "Temp. (F)",
+    "systolicBP" => "SBP",
+    "diastolicBP" => "DBP",
+    "pulseRatePerMinute" => "Pulse",
+    "respirationRatePerMinute" => "Resp.",
+    "pulseOx" => "Pulse Ox.",
+    "smokingStatus" => "Smoking Status",
+    "bmi" => "BMI (kg/m²)",
+];
+
+$contentData = null;
+if (!!@$point->data) {
+    $contentData = json_decode($point->data, true);
+}
+
+if(!$contentData) {
+    $contentData = [
+        "heightInInches" => [
+            "label" => "Ht. (in.)",
+            "value" => "",
+            "date" => "",
+        ],
+        "weightPounds" => [
+            "label" => "Wt. (lbs.)",
+            "value" => "",
+            "date" => "",
+        ],
+        "temperatureF" => [
+            "label" => "Temp. (F)",
+            "value" => "",
+            "date" => "",
+        ],
+        "systolicBP" => [
+            "label" => "SBP",
+            "value" => "",
+            "date" => "",
+        ],
+        "diastolicBP" => [
+            "label" => "DBP",
+            "value" => "",
+            "date" => "",
+        ],
+        "pulseRatePerMinute" => [
+            "label" => "Pulse",
+            "value" => "",
+            "date" => "",
+        ],
+        "respirationRatePerMinute" => [
+            "label" => "Resp.",
+            "value" => "",
+            "date" => "",
+        ],
+        "pulseOx" => [
+            "label" => "Pulse Ox.",
+            "value" => "",
+            "date" => "",
+        ],
+        "smokingStatus" => [
+            "label" => "Smoking Status",
+            "value" => "",
+            "date" => "",
+        ],
+        "bmi" => [
+            "label" => "BMI (kg/m²)",
+            "value" => "",
+            "date" => "",
+        ],
+    ];
+}else {
+    foreach ($vitalLabels as $k => $v) {
+        if (!isset($contentData[$k])) {
+            $contentData[$k] = [
+                "label" => $v,
+                "value" => "",
+                "date" => "",
+            ];
+        }
+    }
+}
+?>
+
+@foreach ($vitalLabels as $k => $v)
+<div class="d-flex vital-item align-items-center">
+        <span class="content-html text-nowrap">
+            <span>{{$v}}:</span>
+            <?php
+            $vital = [];
+            if(isset($contentData[$k])) {
+                $vital = $contentData[$k];
+            }
+            ?>
+            <b>{{ isset($vital["value"]) && !empty($vital["value"]) ? $vital["value"] : '-' }}</b>
+            @if($k === 'bmi' && isset($vital["value"]) && !empty($vital["value"]))
+                <?php $bmi = floatval($vital["value"]); ?>
+                <span class="ml-2 py-1 m-0 font-weight-bold">
+                     @if($bmi < 18.5)
+                        <span class="text-sm text-warning-mellow">(Underweight)</span>
+                     @endif
+                    @if($bmi >= 18.5 && $bmi < 25)
+                        <span class="text-sm text-success">(Healthy Weight)</span>
+                    @endif
+                    @if($bmi >= 25 && $bmi < 30)
+                        <span class="text-sm text-warning-mellow">(Overweight)</span>
+                    @endif
+                    @if($bmi >= 30)
+                        <span class="text-sm text-warning-mellow">(Obese)</span>
+                    @endif
+                </span>
+            @endif
+            @if(!!$vital["date"])
+                <span class="font-weight-normal text-secondary ml-2 text-sm">(as on {{ friendly_date_time($vital["date"], false) }})</span>
+            @endif
+        </span>
+</div>
+@endforeach
+

+ 32 - 0
resources/views/app/patient/prescriptions/client-status-form.blade.php

@@ -0,0 +1,32 @@
+<div class="stag-popup stag-popup-sm mcp-theme-1 min-height-unset" stag-popup-key="client-status-popup">
+    <form method="POST" action="" class="overflow-visible">
+        <h3 class="stag-popup-title mb-2">
+            <span>Client Declared Status</span>
+            <a href="#" class="ml-auto text-secondary"
+               onclick="return closeStagPopup()"><i class="fa fa-times-circle"></i></a>
+        </h3>
+        <div class="mb-2">
+            <label class="text-sm text-secondary mb-1">Status</label>
+            <select class="form-control form-control-sm min-width-unset erx-hcp-pro-select"
+                    v-model="currentPrescriptionClientStatus.status">
+                <option value="">-- select --</option>
+                <option value="CREATED">Created</option>
+                <option value="SENT">Sent</option>
+                <option value="RECEIVED_BY_CLIENT">Received by client</option>
+                <option value="RECEIPT_CONFIRMED_BY_FACILITY">Receipt confirmed by facility</option>
+                <option value="CANCELLED">Cancelled</option>
+            </select>
+        </div>
+        <div class="mb-2">
+            <label class="text-sm text-secondary mb-1">Memo</label>
+            <input type="text" class="form-control form-control-sm min-width-unset"
+                   v-model="currentPrescriptionClientStatus.memo">
+        </div>
+        <div class="d-flex align-items-center justify-content-center mt-3">
+            <button type="button" class="btn btn-sm btn-primary mr-2" v-on:click.prevent="saveClientStatus()">Submit
+            </button>
+            <button type="button" class="btn btn-sm btn-default border" onclick="return closeStagPopup()">Cancel
+            </button>
+        </div>
+    </form>
+</div>

+ 61 - 0
resources/views/app/patient/prescriptions/drug-form.blade.php

@@ -0,0 +1,61 @@
+<div class="stag-popup stag-popup-sm mcp-theme-1" stag-popup-key="prescription-popup-DRUG">
+    <form method="POST" action="" class="overflow-visible">
+        <h3 class="stag-popup-title mb-2">
+            <span>Drug Prescription</span>
+            <a href="#" class="ml-auto text-secondary"
+               onclick="return closeStagPopup()"><i class="fa fa-times-circle"></i></a>
+        </h3>
+
+        <input type="hidden" data-name="medId">
+        <input type="hidden" data-name="routedMedId">
+        <input type="hidden" data-name="routedDosageFormMedId">
+        <input type="hidden" data-name="gcnSeqno">
+
+        <div class="mb-2">
+            <label class="text-sm text-secondary mb-1">Drug</label>
+            <input type="text" class="form-control form-control-sm min-width-unset prescription-medication"
+                   stag-suggest
+                   stag-suggest-ep="/fdb-med-suggest-v2/json">
+        </div>
+
+        <div class="row">
+            <div class="col-4 pr-0">
+                <div class="mb-2">
+                    <label class="text-sm text-secondary mb-1">Frequency</label>
+                    <input type="text" class="form-control form-control-sm min-width-unset"
+                           data-option-list="frequency-options" data-field="frequency"
+                           v-model="currentPrescription_DRUG.clinicalDetailJson.frequency">
+                    <div id="frequency-options" class="data-option-list">
+                        <div>Once a day</div>
+                        <div>Twice a day</div>
+                    </div>
+                </div>
+            </div>
+            <div class="col-4 pr-0">
+                <div class="mb-2">
+                    <label class="text-sm text-secondary mb-1">Dispense</label>
+                    <input type="text" class="form-control form-control-sm min-width-unset"
+                           v-model="currentPrescription_DRUG.clinicalDetailJson.dispense">
+                </div>
+            </div>
+            <div class="col-4">
+                <div class="mb-2">
+                    <label class="text-sm text-secondary mb-1">Refills</label>
+                    <input type="text" class="form-control form-control-sm min-width-unset"
+                           v-model="currentPrescription_DRUG.clinicalDetailJson.refills">
+                </div>
+            </div>
+        </div>
+        <div class="mb-2">
+            <label class="text-sm text-secondary mb-1">Purpose</label>
+            <input type="text" class="form-control form-control-sm min-width-unset"
+                   v-model="currentPrescription_DRUG.clinicalDetailJson.purpose">
+        </div>
+        <div class="d-flex align-items-center justify-content-center mt-3">
+            <button type="button" class="btn btn-sm btn-primary mr-2" v-on:click.prevent="savePrescription()">Submit
+            </button>
+            <button type="button" class="btn btn-sm btn-default border" onclick="return closeStagPopup()">Cancel
+            </button>
+        </div>
+    </form>
+</div>

Some files were not shown because too many files changed in this diff